How to read and write to files easily with java.nio.file package

Prior to Java 7 reading and writing to files in Java was not intuitive. We had to depend on java.io package.

To write to a file you had to use a file writer like this :

                         FileWriter fw = new FileWriter("G://filedemo.txt");
			fw.write(
					"Hello World!\nHow are you \nThis is a sample file written using latest methods of java.nio.file package");
			fw.close();

You had to create a new instance of FileWriter and then also make sure it is closed once the writing is done. If any exception happens before closing it then you should close it again in finally block.

Also to read back from the file you had to use a file reader like this:

	               FileReader fr = new FileReader("G://filedemo.txt");

			int i;
			while ((i = fr.read()) != -1) {
				System.out.print((char) i);

			}
			fr.close();

You need to create a new instance of FileReader and make sure it is closed once the reading is done. Again like FileWriter you need to create a finally block and make sure the FileReader resource is closed there as well.

Also you can read only in bytes , not in strings.

Java 7 came up with java.nio.file package and the design got better.

And then Java 11 came up with new methods to read and write strings to a file. Using strings is the most common use case in most file manipulation programs and yet we had to deal with bytes before this feature.

Now writing a string to a file can be written in a single line:

	Files.writeString(Path.of("G://filedemo.txt"),
					"Hello World!\nHow are you \nThis is a sample file written using latest methods of java.nio.file package");

Files is a utility class provided by java.nio.file package. writeString() writes the string supplied as the second argument to it , to the file. The first argument is the path object representing the file. A path object can be constructed from a file path using Path.of() method.

That’s it!.

No need to close any resource as the Files utility class internally uses an outputstream to write to the file and closes it once it is done.

And similarly reading the contents from a file as a single string can be done using a single line of code:

Files.readString(Path.of("G://filedemo.txt"))

Just like in writing , there is no need of closing resources and the entire content of the file is returned as a string object.

These features are more intuitive and are a better design compared to the previous versions.

Also if you want to write a huge amount of content it is better to use BufferedReader to prevent blocking I/O.

This can be done using the utility method:

Files.newBufferedWriter()

Here is the implementation:

	      String content = "Hello World!\nHow are you \nThis is a sample file written using latest methods of java.nio.file package";

		try (BufferedWriter writer = Files.newBufferedWriter(Path.of("G://filedemo.txt"))) {

			writer.write(content, 0, content.length());

		} catch (IOException x) {

			x.printStackTrace();
		}

The BufferedWriter is automatically closed as it is initialized using try-with-resources statement (parameter to try block) . This is another feature introduced in Java 7 which helps in reducing the verbosity of code as well its efficiency.

Also for reading huge amounts of data , you can use BufferedReader:

Files.newBufferedReader()

Here is the implementation:

	       try (BufferedReader reader = Files.newBufferedReader(Path.of("G://filedemo.txt"))) {
			
			String line = null;
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
			}
		} catch (IOException x) {

			x.printStackTrace();

		}

File manipulation just got easier with the latest versions of Java.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s