file

Java Nio Write File Example

Photo of Aaron WitterAaron WitterOctober 17th, 2016Last Updated: March 12th, 2019
1 5,427 3 minutes read

With this example we are going to demonstrate how to use the Non-blocking I/O API, orNIO.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

TheNIO.2 API was introduced in Java 7 as a replacement for thejava.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.  APath object is a hierarchical representation of the path on a system to the file or directory. Thejava.nio.file.Path interface is the primary entry point for working with theNIO 2 API.

The easiest way to create a Path Object is to use thejava.nio.files.Paths factory class. The class has a staticget()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. Ajava.nio.file.Path , like aFile, 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:

Want to be a Java NIO Master ?
Subscribe to our newsletter and download the JDBCUltimateGuideright now!
In order to help you master Java NIO Library, we have compiled a kick-ass guide with all the major Java NIO features and use cases! Besides studying them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

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

 

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Aaron WitterAaron WitterOctober 17th, 2016Last Updated: March 12th, 2019
1 5,427 3 minutes read
Photo of Aaron Witter

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.

Related Articles

Bipartite Graph

java.nio.file.Path Example

November 13th, 2014
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.