file

Java Nio Write File Example

With this example we are going to demonstrate how to use the Non-blocking I/O API, or NIO.2 API (NIO API) for short, to write data to a file. The examples in this article are compiled and run in a Mac OS unix environment.

Please note that Java SE 8 is required to run the code in this article.
 
 
 
 
 
 
 

1. Introduction to the NIO API

The NIO.2 API was introduced in Java 7 as a replacement for the java.io.File class. It provides a flexible, and intuitive API for use with files.

2. Creating a NIO Path

In order to write a file to the file system we must first create a Path for the destination of the file.  A Path object is a hierarchical representation of the path on a system to the file or directory. The java.nio.file.Path interface is the primary entry point for working with the NIO 2 API.

The easiest way to create a Path Object is to use the java.nio.files.Paths factory class. The class has a static get()method which can be used to obtain a reference to a file or directory. The method accepts either a string, or a sequence of strings(which it will join to form a path) as parameters. A java.nio.file.Path , like a File, may refer to either an absolute or relative path within the file system.  This is displayed in the following examples:

1Path p1 = Paths.get("cats/fluffy.jpg");
2Path p2 = Paths.get("/home/project");
3Path p3 = Paths.get("/animals", "dogs", "labradors");

In the above:

  • p1 creates a relative reference to a file in the current working directory.
  • p2 creates a reference to an absolute directory in a Unix based system.
  • p3 creates a reference to the absolute directory /animals/dogs/labradors

3. Writing files with the NIO API

Once we have a Path Object we are able to execute most of the operations that were previously possible with java.io.File.

3.1 Using NIO API with write()

The Files.write() method is an option when writing strings to file. It is cleanly and concisely expressed. It is not a good idea to use a method like this to write larger files, due to its reliance on byte arrays. As shown below there are more efficient ways of handling these.

Path path = Paths.get("src/main/resources/question.txt");

String question = "To be or not to be?";
    
Files.write(path, question.getBytes());

3.2 Using NIO API with newBufferedWriter()

The NIO.2 API has methods for writing files using java.io streams.  The Files.newBufferedWriter(Path,Charset) writes to the file at the specified Path location, using the user defined Charset for character encoding. This BufferedWriter method is preferential due to its efficient performance especially when completing a large amount of write operations. Buffered operations have this effect as they aren’t required to call the operating system’s write method for every single byte, reducing on costly I/O operations. Here’s an example:

Path path = Paths.get("src/main/resources/shakespeare.txt");
try(BufferedWriter writer = Files.newBufferedWriter(path, Charset.forName("UTF-8"))){
writer.write("To be, or not to be. That is the question.");
}catch(IOException ex){
ex.printStackTrace();
}

This method will create a new file at the given path, or overwrite it if it already exists.

3.3 Using NIO API to copy a file with an Outputstream

In this example we use the NIO API in conjunction with an output stream to copy a file and its contents from one file to a new instance with a new name. We achieve this by using the Files.copy() method, which accepts (Path source, Outputstream os) as its parameters.

Path oldFile = Paths.get("src/main/resources/", "oldFile.txt");
Path newFile = Paths.get("src/main/resources/", "newFile.txt");
   try (OutputStream os = new FileOutputStream(newFile.toFile())) {

      Files.copy(oldFile, os);

    } catch (IOException ex) {
    ex.printStackTrace();
    }

The code above is an example of the try with resources syntax which was introduced in Java 7 and made it easier handle exceptions while correctly closing streams and other resources which are used in a try-catch block. FileOutputStream is used to handle binary data.

4. Summary

In this article we’ve introduced you a couple ways to use the NIO API to write a file to your file system. Along the way we’ve touched upon the Path object.

5. Download The Source Code

This was an example of writing to a file with Java NIO2 API.

Download
You can download the full source code of this example here: Java Nio Write File Example

 

Aaron Witter

Aaron is a self-taught Certified Oracle Java programmer, with experience delivering high quality Java applications for a variety of UK Government Departments. Aaron has worked on projects ranging from the overhaul of the National Statistics website to delivering a portal for quality management in the National Health Service.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Joe R
Joe R
2 years ago

Thank you

Back to top button