Java Reference
In-Depth Information
more data to process—it just hasn't arrived yet until the user types it in. That's
why in previous examples we've used special sentinel values to determine the end
of interactive input.
However, the fact that a Scanner object is an iterator is particularly helpful
when the scanner is being used to process input from a source that has a specific
end point, such as processing the lines of a data file or processing the parts of a
character string. Let's examine an example of this type of processing.
Reading Text Files
Suppose we have an input file called urls.inp that contains a list of URLs that
we want to process in some way:
www.google.com
www.linux.org/info/gnu.html
thelyric.com/calendar/
www.cs.vt.edu/undergraduate/about
youtube.com/watch?v=EHCRimwRGLs
The program shown in Listing 5.10 reads the URLs from this file and dissects
them to show the various parts of the path. It uses a Scanner object to process the
input. In fact, it uses multiple Scanner objects—one to read the lines of the data
file and another to process each URL string.
LISTING 5.10
//********************************************************************
// URLDissector.java Author: Lewis/Loftus
//
// Demonstrates the use of Scanner to read file input and parse it
// using alternative delimiters.
//********************************************************************
import java.util.Scanner;
import java.io.*;
public class URLDissector
{
//-----------------------------------------------------------------
// Reads urls from a file and prints their path components.
//-----------------------------------------------------------------
public static void main (String[] args) throws IOException
{
 
Search WWH ::




Custom Search