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();
        }
    }
}

How do I check if a file exists?

To check if a file, or a directory exists we can utilize java.io.File.exists() method. This method return either true or false. Before we can check whether its exists or not we need to create an instance of File that represent an abstract path name of the file or directory. After we have the File instance we can call the exists() method to validate it.

package org.kodejava.io;

import java.io.File;
import java.io.FileNotFoundException;

public class FileExists {
    public static void main(String[] args) throws Exception {
        // Create an abstract definition of configuration file to be
        // read.
        File file = new File("applicationContext-hibernate.xml");

        // Print the exact location of the file in file system.
        System.out.println("File = " + file.getAbsolutePath());

        // If configuration file, applicationContext-hibernate.xml
        // does not exist in the current path throws an exception.
        if (!file.exists()) {
            String message = "Cannot find configuration file!";
            System.out.println(message);
            throw new FileNotFoundException(message);
        }

        // Continue with application logic here!
    }
}

How do I create and write data into text file?

Here is a code example for creating text file and put some texts in it. This program will create a file called write.txt. To create and write a text file we do the following steps:

File file = new File("write.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

Below is the complete code snippet:

package org.kodejava.io;

import java.io.*;

public class WriteTextFileExample {
    public static void main(String[] args) {
        File file = new File("write.txt");

        try (Writer writer = new BufferedWriter(new FileWriter(file))) {
            String contents = "The quick brown fox" + 
                System.getProperty("line.separator") + "jumps over the lazy dog.";

            writer.write(contents);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

To read a text file see the following example: How do I read a text file using BufferedReader?.

How do I read a text file using BufferedReader?

The code snippet below is an example of how to read a text file using BufferedReader class from the java.io package. This snippet read a text file called README.md and print out its content.

To create an instance of java.io.BufferedReader we do the following steps:

File file = new File("README.md");
FileReader fileReader = new FileReader(file));
BufferedReader bufferedReader = new BufferedReader(fileReader);

Let’s see the complete code snippet.

package org.kodejava.io;

import java.io.*;

public class ReadTextFileExample {
    private static final String LINE_SEPARATOR = System.getProperty("line.separator");

    public static void main(String[] args) {
        File file = new File("README.md");
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            StringBuilder contents = new StringBuilder();
            String text;
            while ((text = reader.readLine()) != null) {
                contents.append(text).append(LINE_SEPARATOR);
            }

            System.out.println(contents.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

You can also try to use the following example to read a file, How do I read text file content line by line using commons-io?. To create and write a text file see the following example: How do I create and write data into text file?.