Friday, September 16, 2011

JAVA FileRead

Read file into ArrayList

public static ArrayList<String> FileRead(String FileName)
{
     /*
     * (c) John Minkjan
     * 101Java.blogspot.com
     * 2011 till 2031
     * Usage:
     * Object[] elements = jGeneral.FileRead("c:\\java\\out.txt").toArray();
     * for(int i=0; i < elements.length ; i++)       
           System.out.println(i + " " +elements[i]);
     */
     ArrayList<String> lineArr = new ArrayList<String>();
    try {          
        FileInputStream fstream = new FileInputStream(FileName);
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader( in ));
        String strLine;
        //Read File Line By Line and add to Arraylist
        while ((strLine = br.readLine()) != null) {
            lineArr.add(strLine);              
        }
        //Close the input stream
        in .close();
    } catch (Exception e) { //Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }
return lineArr;
}

Till Next Time

No comments:

Post a Comment