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

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s