Java - file reading function

This code using java.util.Scanner class to read file to String, and very helpful for Java Application developing.

private static String readFile(String pathname) throws IOException {
   File file = new File(pathname);
   StringBuilder fileContents = new StringBuilder((int)file.length());
   Scanner scanner = new Scanner(file);
   String lineSeparator = System.getProperty("line.separator");
   try {
       while(scanner.hasNextLine()) {       
           fileContents.append(scanner.nextLine() + lineSeparator);
       }
       return fileContents.toString();
   } finally {
       scanner.close();
   }
}

Leave a Reply

Powered by Blogger.