Friday, May 13, 2011

Read File Contents into Java ArrayList

The following method reads file contents into an ArrayList. Each element of the ArrayList will contain a line from the file.

public ArrayList readFile(String fname){
    String line;
    StringBuffer sb = new StringBuffer();
    ArrayList al = new ArrayList();
    try {
     FileInputStream fis = new FileInputStream(fname);
        BufferedReader reader=
          new BufferedReader
            (new InputStreamReader(fis));
        while((line = reader.readLine()) != null) {
   al.add(line);
  }
        reader.close();
 }
 catch (IOException e) {
     System.err.println("*** IOexception ***" + e.getMessage());
 }
 return al;
 }

No comments:

Post a Comment