Thursday, 9 May 2013

Java 7 : I/O using the NIO package

The NIO package in Java 7 is an important and much needed update to the Java I/O mechanism. With regards to I/O, the java.nio.file and the java.nio.file.attribute packages are key. An important change to the previous mechanism is the introduction of the Path object which is analogous to the File object. Other changes are documented here.

A simple example that reads in a list of entries from a text file and appends a special character at the end of every line is given below:

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

public class FileReaderAndSpecialCharacterInserter {
     private static String SPECIAL_CHARACTER = ",";

       * @param args
     public static void main(String[] args) {
     FileReaderAndSpecialCharacterInserter fileReader = new FileReaderAndSpecialCharacterInserter();

                private void readFile()
                                StringBuffer outputString = new StringBuffer();
                                Path path = Paths.get("c:/test.txt");
                                Charset charset = Charset.forName("US-ASCII");
                                try (BufferedReader reader = Files.newBufferedReader(path, charset))
                                    String line = null;
                                    while ((line = reader.readLine()) != null)
                                catch (IOException x)
                                    System.err.format("IOException: %s%n", x);
                                System.out.print("The final output string is : -> " + outputString.toString());

As evident in the example above, the Path object sets up a channel to the file to be read and essays the role played by the File object in the I/O mechanism available upto Java 6. The advantages of this new File I/O mechanism are mainly scalability and error handling  and are documented in detail here.

No comments: