Wednesday, March 9, 2011

How to read a file line by line in Java

In this example I explain how to read a text file line by line and add the lines to a List.
 import java.io.BufferedReader;
 import java.io.FileReader;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
 import javax.swing.JOptionPane;


 public static void main(String[] args) throws IOException {
   String fileName = "c:\\camera.log"; \\This is the path to your
                                       file
   FileReader reader = new FileReader(fileName);
   BufferedReader buffReader = new BufferedReader(reader);
   List<string> linesList = new ArrayList<string>();
   String line;
   while((line = buffReader.readLine()) != null){
     linesList.add(line);
   }
   //For the purpose of this example I just show a message box to
    display the content of the file.
   JOptionPane.showMessageDialog(null, linesList.toArray());
}

No comments:

Post a Comment