next up previous
Next: Renaming and deleting a Up: Unit 09 Previous: Loop schema for reading

Reading from a file using the Scanner class

An alternative way to read from a file is by using the Scanner class, which has a constructor that allows one to initialize a Scanner object so that it reads from a file (instead of standard input).

For example:

File f = new File("myNumbers")
Scanner sc = new Scanner(f);

Then, using the Scanner object, we can use the next() and hasNext() methods, or their variants for reading primitive types (such as nextInt() and hasNextInt()), to read from the file.

For example, to sum up numbers read from a file:

File f = new File("myNumbers")
Scanner sc = new Scanner(f);

long sum = 0;
while (sc.hasNextLong()) {
  long x = sc.nextLong();
  sum = sum + x;
}
System.out.println(sum);


next up previous
Next: Renaming and deleting a Up: Unit 09 Previous: Loop schema for reading