e!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
Scanner
object just like keyboard
Scanner
gets its data from
System.out
and System.in
which are called stream.
Scanner
Scanner
objects that read their data from an external file are created using a File
object (rather than
System.in
import java.io.*; import java.util.*; … public static void main(String [] args) throws Exception { Scanner scanner = new Scanner(new File("data.text")); // preparing to read data from the file data.text …
File
object requires:
java.io
throws Exception
to the header line of the (main
) method informing
the compiler that you are aware that using the file may potentially cause a problem (i.e., the file not
existing).
FileNotFoundException
at Compilation and Executionnew File
does not have to exist when you compile the file
throws Exception
to the first line of your method.
FileNotFoundException
and will terminate your program with a message to that effect.
Math.round
method by reading in a header value (i.e., number of data items to read in)
from the file data.text
followed by that number of floating point numbers (doubles). For each number read in, print out the number
and it's rounded value using Math.round
.
Codeimport java.io.*; import java.util.*; public class Rounder { public static void main(String [] args) throws Exception { Scanner scanner = new Scanner(new File("data.text")); int howMany = scanner.nextInt(); for (int i = 1; i <= howMany; i = i + 1) { double d = scanner.nextDouble(); System.out.println(d + " rounds to " + Math.round(d)); } } }
data.text6 3.2 5.7 4.5 9.0 12 16.4
Stdout3.2 rounds to 3 5.7 rounds to 6 4.5 rounds to 5 9.0 rounds to 9 12.0 rounds to 12 16.4 rounds to 16
next
and nextLine
Methodsnext
method of Scanner
— it reads the next piece of data and returns
it as a String
next
reads in a sequence of characters until it encounters a whitespace character —
a blank, tab, or newline (end of the line) character.
Weiss Geraldthen after one calls
next
:
String name = scanner.next();the
String
variable name
would contain Weiss
(i.e., scanner
would
stop reading characters when it encounters the blank after the second 's' in Weiss.
nextLine
reads in an entire line at a time and (line next
) returns it as a
String
.
String name = scanner.nextLine();the
String
variable name
would contain Weiss Gerald
2900 Bedford Avenueor a full (i.e., first and last) name:
Gerald Weissthe individual elements (e.g. the house number (
2900
), street name (Bedford
),
street type, (Avenue
, first name (Gerald
), and last name (Weiss
)
could be
houseNumber
, streetName
, … lastName
)
using repeated calls to next
, or
streetAddress
, fullName
) using nextLine
)
nextLine
together with the other Scanner
methods (next
, nextInt
,
nextDouble
) can easily result in what seems to be strange results, and is best avoided (for the beginner at least).
Scanner
for the keyboard uses the already familiar System.in
as its data source.
String
variable
using this (keyboard) scanner.
Scanner
for the file uses a File
object whose name is supplied by the String
variable
read in from the keyboard (rather than a literal).
import java.io.*; // for the File object import java.util.*; // for the Scanner objects … Scanner keyboard = new Scanner(System.in); // keyboard scanner System.out.print("Enter the name of the data file: "); String filename= keyboard.next(); Scanner datafile = new Scanner(new File(filename)); // scanner for the data file // can now use the datafile scanner to read in the data …
*** Found it!
;
Codeimport java.io.*; import java.util.*; public class Finder { public static void main(String [] args) throws Exception { Scanner keyboard = new Scanner(System.in); System.out.print("Which file would you like to search? "); String filename = keyboard.next(); System.out.print("Which number would you like to find? "); int theNumber = keyboard.nextInt(); Scanner dataFile = new Scanner(new File(filename)); int n = dataFile.nextInt(); // get number of numbers in file for (int i = 1; i <= n; i = i + 1) { int num = dataFile.nextInt(); if (theNumber == num) System.out.println("*** Found it!"); } } }
Stdindata.text 4
data.text3 2 4 6
StdoutWhich file would you like to search? Which number would you like to find? *** Found it!
Here is a sample execution of the program. User input is in bold. Which file would you like to search? data.text Which number would you like to find? 4 *** Found it!
PrintStream
ClassScanner
based on System.in
) or
a file (a Scanner
based on a File
object)
PrintStream
object is created; this is done as follows:
PrintStream ps = new PrintStream(filename);for example:
PrintStream ps = new PrintStream("results.text");
System.out
is itself a PrintStream
object, so we already know all
the methods available to our file-based PrintStream
object: print
,
println
, etc.
close
method:
ps.close();this ensures the file is properly saved to disk
Rewrite P05.1 so that the output is written to the file data.output
(rather than the screen)
Codeimport java.io.*; import java.util.*; public class Rounder { public static void main(String [] args) throws Exception { Scanner scanner = new Scanner(new File("data.text")); PrintStream ps = new PrintStream("data.output"); int howMany = scanner.nextInt(); for (int i = 1; i <= howMany; i = i + 1) { double d = scanner.nextDouble(); ps.println(d + " rounds to " + Math.round(d)); } } }
data.text6 3.2 5.7 4.5 9.0 12 16.4
data.output3.2 rounds to 3 5.7 rounds to 6 4.5 rounds to 5 9.0 rounds to 9 12.0 rounds to 12 16.4 rounds to 16
P05.4 FileCopier
Write a program that prompts the user for the name of an existing file and the name of a second file to which the contents of the first file should
be copied. The existing file contains a header file (an integer) followed by that number of doubles, all of which should be copied to the destination file..
Code
Notes
Notes
Notes
Notes
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
public class FileCopier {
public static void main(String [] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println("File to copy from: ");
String infilename = keyboard.next();
System.out.println("File to copy to: ");
String outfilename = keyboard.next();
Scanner infile = new Scanner(new File(infilename));
PrintStream outfile= new PrintStream(outfilename);
int numValues = infile.nextInt();
outfile.println(numValues); // have to copy the header as well
outfile.println(); // blank line to separate the header from the actual data
for (int i = 1; i <= numValues; i = i + 1) {
double num = infile.nextDouble();
outfile.println(num);
}
infile.close();
outfile.close();
System.out.println(numberOfValues + " values copied from " + infilename + " to " + outfilename);
}
}
stdin
(the keyboard), represented by System.in
stdout
(the screen) reoresented by System.out
infilename
, and represented by the variable infile
outfilename
, and represented by the variable outfile
5
12.1 6.7 3.5 9 45.2
nextDouble
simply reads in values expecting them to be doubles, and stops reading characters when it encounters whitespace,
be it a newline, a tab, or a blank
oldfile.data
newfile.text
5
12.1
6.7
3.5
9.0
45.2
nextDouble
, this format would work if it was the input file to this program.
File to copy from:
File to copy to:
5 values copied from oldfile.data to newfile.text
The
For technical reasons beyond the scope of this class (or at least for now), there is a second class — PrintWriter
ClassPrintWriter
— that
provides print
and println
methods that operate identically (as far as we are concerned) to those of the PrintStream
class.
And for equally obscure reasons, CodeLab exercises on files request the use of PrintWriter
rather than PrintStream
.
Files used in Lecture 5
Lab for Lecture 5