Reading files in Java IO/NIO

This is an example of reading files with both IO and NIO. NIO is in JDK since 1.4, but isn’t very enforced for using as primary IO and many developers are still using IO. For small files performance are pretty much the same, but for larger files NIO is superior than IO. So, here are the two examples:

IO

public class FileReading {
      public FileReading() {}
      public String read(String filename) {
              StringBuilder mailContent = new StringBuilder();
              File f = new File(filename);
              try (BufferedReader reader = new BufferedReader(new FileReader(f))) {
              String line = "";
              while ((line = reader.readLine()) != null) {
                  mailContent.append(line).append("\n");
              }
      } catch (IOException e) {
           System.err.println(e.getLocalizedMessage());
      }return mailContent.toString();
}
}

NIO

public class FileReading {
 private final static int kb = 1024;
 public FileReading() {}
 public String read(String filename) {
    StringBuilder result = new StringBuilder();
    try (ReadableByteChannel fileInput = new FileInputStream(new File(filename)).getChannel()) {
         ByteBuffer buff = ByteBuffer.allocate(2 * kb);
         while (fileInput.read(buff) != -1) {
             buff.flip();
             byte[] byteArray = new byte[buff.remaining()];
             buff.get(byteArray);
             result.append(new String(byteArray));
             buff.rewind();
         }
    } catch (Exception e) {
          System.err.println(e.getLocalizedMessage());
    }
    return result.toString();
   }
}
Advertisements

Hello world!

Welcome to WordPress.com! This is your very first post. Click the Edit link to modify or delete it, or start a new post. If you like, use this post to tell readers why you started this blog and what you plan to do with it.

Happy blogging!