RU beehive logo ITEC dept promo banner
ITEC 120
2019fall
asbrennem
ibarland

Reading from a file

reading files and web pages

We've seen we can use java.util.Scanners to read input from the keyboard:

java.util.Scanner scnr = new java.util.Scanner( System.in );
System.out.print("Shout! (or ^C to indicate end-of-file) ");
while (scnr.hasNext()) {
  String msg = scnr.next();
  System.out.println( msg + ", echo, echo..." );
  System.out.print( "Shout more! (or ^C to indicate end-of-file) " );
  }
Really, a Scanner is an object who can group individual characters into meaningful units (words, doubles, etc.).

But a Scanner can read information from any source of characters: they can read information from a file, a web page, or even a String inside your program. When you call the constructor, you just pass in a source of characters.


nextInt vs. nextLine

Unintutively, consider:

import java.util.Scanner;
Scanner s1 = new Scanner( "line 1  \n   lion 2  \n    lyin' 3\n Last line; bye!" );
s1.next()              // returns "line"
s1.nextInt()           // returns 1

s1.next()              // returns "lion"
s1.nextInt()           // returns 2
s1.nextLine()          // returns "  " -- I guess that makes sense.

s1.next()              // returns "lyin'"
s1.nextInt()           // returns 3
s1.nextLine()          // returns "" -- beware!
In general, when you intermingle calls to nextLine and next/nextInt/etc., be very careful!

Alternate strategy:

Scanner s2 = new Scanner( "line 1  \n   lion 2  \n    lyin' 3\n Last line; bye!" );

String entireLine = s2.nextLine();
Scanner scanAssistant = new Scanner( entireLine );
scanAssistant.next();    // returns "line"
scanAssistant.nextInt(); // returns 1

String entireLine = s2.nextLine();
Scanner scanAssistant = new Scanner( entireLine );
scanAssistant.next();    // returns "lion"
scanAssistant.nextInt(); // returns 2

String entireLine = s2.nextLine();
Scanner scanAssistant = new Scanner( entireLine );
scanAssistant.next();    // returns "lyin'"
scanAssistant.nextInt(); // returns 3


1 In this case, if you try it out, you realize that web pages are written in html; in html the notion of the next word is different from where the next whitespace occurs. Indeed, people have written specialized classes which extend Scanner to so that the next method returns the next word in a way that is appropriate for html.      

logo for creative commons by-attribution license
This page licensed CC-BY 4.0 Ian Barland
Page last generated
Please mail any suggestions
(incl. typos, broken links)
to ibarlandradford.edu
Rendered by Racket.