Sunday, January 15, 2017

How to Read files in java

1.Using Scanner

Scanner sc= new Scanner(new File("filename.txt") )

Methods inside scanner

1)hasNext(),next(),nextLine(),useDelimiter()
hasNext()--returns true until there is a token

1) By default, a scanner uses white space (can be space,tab,or new line) to separate tokens

  Delimiter can also be changed by--- sc.useDelimiter(",\\s*");

Useful Stackoverflow links:
http://stackoverflow.com/questions/41668412/java-scanner-is-not-working-while-reading-a-file


2.Using BufferReader

br = new BufferedReader(new FileReader(FILENAME));
while ((strLine = br.readLine()) != null)   {
String[] arr = strLine.split("\\s+"); //Breaking each line into array of words
Item item = new Item(arr[0],arr[1],Integer.parseInt(arr[2]));
list.add(item);
}

No comments:

Post a Comment