Wednesday, May 18, 2011

Read a file line by line

 In this example I explain how to read a 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"; \\Path to your file
  FileReader reader = new FileReader(fileName);
  BufferedReader buffReader = new BufferedReader(reader);
  List linesList = new ArrayList();
  String line;
  while((line = buffReader.readLine()) != null){
    linesList.add(line);
  }
  //For 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