How do I read all lines from a file?

The java.nio.file.Files.readAllLines() method read all lines from a file. This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. Bytes from the file are decoded into characters using the specified charset.

Note that this method is intended for simple cases where it is convenient to read all lines in a single operation. It is not intended for reading in large files. This method is available in Java 7.

package org.kodejava.example.nio;

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class ReadFileAsListDemo {
    public static void main(String[] args) {
        ReadFileAsListDemo demo = new ReadFileAsListDemo();

    private void readFileAsList() {
        String fileName = "/data.txt";

        try {
            URI uri = this.getClass().getResource(fileName).toURI();
            List<String> lines = Files.readAllLines(Paths.get(uri),

            for (String line : lines) {
        } catch (Exception e) {

How do I use Java NIO to copy file?

This program is an example how we use the New IO API in Java programming. The API is in the java.nio.* package. It requires at least Java 1.4 because the API was first included in this version. The java.nio is a block based IO processing, instead of a stream based IO which is the old version IO processing in Java.

package org.kodejava.example.nio;

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class CopyFileExample {
    public static void main(String[] args) throws Exception {
        String source = "medical-report.txt";
        String destination = "medical-report-final.txt";

        FileInputStream fis = new FileInputStream(source);
        FileOutputStream fos = new FileOutputStream(destination);

        FileChannel fci = fis.getChannel();
        FileChannel fco = fos.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (true) {
            int read =;
            if (read == -1) {