How do I create a java.nio.Path?

The following code snippet show you how to create a Path. A Path (java.nio.Path) in an interface that represent a location in a file system, such as C:/Windows/System32 or /usr/bin.

To create a Path we can use the java.nio.Paths.get(String first, String... more) methods. Below you can see how to create a Path by passing only the first string and by passing a first string plus some varargs string.

package org.kodejava.io;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathCreate {
    public static void main(String[] args) {
        // Create a Path that represents Windows installation location.
        Path windows = Paths.get("C:/Windows");

        // Check to see if the path represent a directory.
        if (Files.isDirectory(windows)) {
            // do something
        }

        // Create a Path that represent Windows programs installation location.
        Path programFiles = Paths.get("C:/Program Files");
        Files.isDirectory(programFiles);

        // Create a Path that represent the notepad.exe program
        Path notepad = Paths.get("C:/Windows", "System32", "notepad.exe");

        // Check to see if the path represent an executable file.
        if (Files.isExecutable(notepad)) {
            // do something
        }
    }
}

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 since Java 7.

package org.kodejava.io;

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

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

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

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

            for (String line : lines) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

How do I create a NIO Buffer?

This post show you how to use the java.nio buffer such as ByteBuffer, CharBuffer, DoubleBuffer, etc. To create a buffer you can use the allocate(int capacity) method. Each buffer object has the allocate(int capacity) method. You need to pass the value of the capacity of the buffer to be created when calling this method.

package org.kodejava.io;

import java.nio.*;

public class BufferAllocate {
    public static void main(String[] args) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(64);
        CharBuffer charBuffer = CharBuffer.allocate(64);
        ShortBuffer shortBuffer = ShortBuffer.allocate(64);
        IntBuffer intBuffer = IntBuffer.allocate(64);
        LongBuffer longBuffer = LongBuffer.allocate(64);
        FloatBuffer floatBuffer = FloatBuffer.allocate(64);
        DoubleBuffer doubleBuffer = DoubleBuffer.allocate(64);
    }
}

How do I use Java NIO to copy file?

The following code snippet show you how to copy a file using the NIO API. The NIO (New IO) 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.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;

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 inputChannel = fis.getChannel();
        FileChannel outputChannel = fos.getChannel();

        // Create a buffer with 1024 size for buffering data
        // while copying from source file to destination file.
        // To create the buffer here we used a static method
        // ByteBuffer.allocate()
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        // Here we start to read the source file and write it
        // to the destination file. We repeat this process
        // until the read method of input stream channel return
        // nothing (-1).
        while (true) {
            // Read a block of data and put it in the buffer
            int read = inputChannel.read(buffer);

            // Did we reach the end of the channel? if yes
            // jump out the while-loop
            if (read == -1) {
                break;
            }

            // flip the buffer
            buffer.flip();

            // write to the destination channel and clear the buffer.
            outputChannel.write(buffer);
            buffer.clear();
        }
    }
}