Code:import java.io.*; import java.util.*; public class ReadTextFile { /** * Fetch the entire contents of a text file, and return it in a String. * This style of implementation does not throw Exceptions to the caller. * * @param aFile is a file which already exists and can be read. */ static public ArrayList getContents(File aFile) { ArrayList arData = new ArrayList(); //...checks on aFile are elided try { //use buffering, reading one line at a time //FileReader always assumes default encoding is OK! BufferedReader input = new BufferedReader(new FileReader(aFile)); try { String line = null; //not declared within while loop /* * readLine is a bit quirky : * it returns the content of a line MINUS the newline. * it returns null only for the END of the stream. * it returns an empty String if two newlines appear in a row. */ while (( line = input.readLine()) != null){ int index =line.indexOf(':'); if(index != -1 ) { arData.add(line.substring(0,index));//name arData.add(line.substring(index+1,line.length()));//value } } } finally { input.close(); } } catch (IOException ex){ ex.printStackTrace(); } return arData; } /** Simple test harness. */ public static void main (String [] args) throws IOException { String fName="Demo.txt"; if (args.length >0) { fName=args[0]; } File testFile = new File(fName); System.out.println(getContents(testFile)); } }


Reply With Quote




Bookmarks