Search This Blog

How to read file in Java


Reading file is a very common scenario. There are different ways to read a file in Java using java’s specific reading classes and also using third party utility jars. Lets look at some of the ways of reading files in java

  1. Using Google’s Guava 
List<String> guavaList = Files.readLines(new File("/home/myfiles/test.dat"), Charsets.UTF_8);
  1. Using Apache Commons IO

List<String> apacheList = FileUtils.readLines(new File("/home/myfiles/test.dat"));


Both of these methods will read whole file line by line and will return a List of String with each line as list’s content. Now since it reads the whole file at once it would require to load the file in memory. This would not be a good way to read large files. For reading large files we can consider using BufferedReader which provides the stream from file and make data available.

Apache commons also provide the utility method which reads the file line by line using a LineIterator. LineIterator works similar to the iterators we have in java for iterating different collections (check here).

sample code as below

FileInputStream fi = new FileInputStream(new File("c:/home/myfiles/test.dat"));
BufferedReader br = new BufferedReader(new InputStreamReader(fi));
System.out.println("***** Using Buffered Reader *****");
String line=null;
while((line = br.readLine())!=null){
System.out.println(line);
}
br.close();


using apache commons

LineIterator iterator = FileUtils.lineIterator(new File("c:/home/myfiles/test.dat"));


You can find the same code @ git 



No comments:

Post a Comment