Professional Documents
Culture Documents
Chapter 10 Streams Streams: File I/O
Chapter 10 Streams Streams: File I/O
Chapter 10
• A stream is an object that enables the flow of
File I/O p g
data between a program and some I/O device
or file
– If the data flows into a program, then the stream
If the data flows into a program then the stream
is called an input stream
– If the data flows out of a program, then the
If th d t fl t f th th
stream is called an output stream
Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 10‐2
Some Methods of the Class PrintWriter
Reading From a Text File Using Scanner
Reading From a Text File Using Scanner
(Part 3 of 3)
• Th
The class Scanner
l S can be used for reading from the
b df di f th
keyboard as well as reading from a text file
– Simply replace the argument System.in
S p y ep ace t e a gu e t Syste . (to (to the Scanner
t e Sca e
constructor) with a suitable stream that is connected to the text file
Scanner StreamObject =
new Scanner(new FileInputStream(FileName));
• Methods of the Scanner class for reading input behave the
g y g
same whether reading from the keyboard or reading from a
text file
– For example, the nextInt and nextLine methods
Reading Input from a Text File Using Scanner Reading Input from a Text File Using Scanner
(Part 3 of 4) (Part 4 of 4)
Checking for the End of a Text File with Checking for the End of a Text File with
hasNextLine (Part 2 of 4) hasNextLine (Part 3 of 4)
Checking for the End of a Text File with Methods in the Class Scanner
hasNextInt (Part 2 of 2) (Part 1 of 11)
Methods in the Class Scanner Methods in the Class Scanner
(Part 4 of 11) (Part 5 of 11)
Methods in the Class Scanner Methods in the Class Scanner
(Part 8 of 11) (Part 9 of 11)
Reading From a Text File Using
Reading From a Text File Using BufferedReader
Reading From a Text File Using BufferedReader
BufferedReader
• Th
The class BufferedReader
l B ff dR d is a stream class that can be
i t l th t b • Like the classes PrintWriter and Scanner,
used to read from a text file BufferedReader has no constructor that takes a file
– An object of the class BufferedReader
object o t e c ass u e ed eade has the methods read
as t e et ods ead aand
d name as its argument
name as its argument
readLine
– It needs to use another class, FileReader, to convert the file
• A program using BufferedReader, like one using name to an object that can be used as an argument to its (the
PrintWriter will start with a set of import statements:
PrintWriter, will start with a set of import BufferedReader) constructor
BufferedReader) constructor
import java.io.BufferedReader; • A stream of the class BufferedReader is created and
import
p j
java.io.FileReader; connected to a text file as follows:
import java.io.FileNotFoundException; BufferedReader readerObject;
import java.io.IOException; readerObject = new BufferedReader(new
FileReader(FileName));
FileReader(FileName))
– This opens the file for reading
Reading Input from a Text File Using Reading Input from a Text File Using
BufferedReader (Part 2 of 3) BufferedReader (Part 3 of 3)
• A program using a BufferedReader object in
this way may throw two kinds of exceptions
– An attempt to open the file may throw a
FileNotFoundException (which in this case
has the expected meaning)
– An invocation of readLine may throw an
IOE
IOException
ti
– Both of these exceptions should be handled
Some Methods of the Class BufferedReader
(Part 2 of 2) Reading Numbers
Reading Numbers
• Unlike the Scanner class, the class
BufferedReader has no methods to read a number
from a text file
from a text file
– Instead, a number must be read in as a string, and then
converted to a value of the appropriate numeric type using one
of the wrapper classes
of the wrapper classes
– To read in a single number on a line by itself, first use the
method readLine, and then use Integer.parseInt,
D bl t t t th t i i t
Double.parseDouble, etc. to convert the string into a
D bl
number
– If there are multiple numbers on a line, StringTokenizer
can be used to decompose the string into tokens, and then the
b d d h i i k d h h
tokens can be converted as described above
Path Names
Path Names Path Names
Path Names
• A path name
h not only gives the name of the
l i h f h • The way path names are specified depends on the
file, but also the directory or folder in which operating system
the file exists – A typical UNIX path name that could be used as a file
• A full path name
f p ggives a complete path name,
p p , name argument is
"/user/sallyz/data/data.txt"
starting from the root directory
– A BufferedReader input stream connected to this
• A relative path name
A relative path name gives the path to the file,
gives the path to the file fil i
file is created as follows:
d f ll
starting with the directory in which the BufferedReader inputStream =
program is located
program is located new BufferedReader(new
FileReader("/user/sallyz/data/data.txt"));
System.in, System.out, and System.in, System.out, and
System.err System.err
• Redirecting System.err: catch(FileNotFoundException e)
{
public void getInput()
System.err.println("Input file not found");
{
}
. . .
finally
PrintStream errStream = null;
{
try
. . .
{
errStream.close();
();
errStream
St = new P
PrintStream(new
i tSt (
}
FileOuptputStream("errMessages.txt"));
}
System.setErr(errStream);
. . . //Set up input stream and read
}
Some Methods in the Class File Some Methods in the Class File
(Part 2 of 5) (Part 3 of 5)
Binary Files
Binary Files Writing Simple Data to a Binary File
Writing Simple Data to a Binary File
• Bi
Binary files store data in the same format used by
fil t d t i th f t db • Th
The class ObjectOutputStream
l Obj tO t tSt i
is a stream class that can
t l th t
computer memory to store the values of variables be used to write to a binary file
– No
No conversion needs to be performed when a value is
conversion needs to be performed when a value is – An
An object of this class has methods to write strings, values of
object of this class has methods to write strings, values of
stored or retrieved from a binary file primitive types, and objects to a binary file
• Java binary files, unlike other binary language files, • A program using ObjectOutputStream needs to import
are portable
bl several classes from package java io:
several classes from package java.io:
import java.io.ObjectOutputStream;
– A binary file created by a Java program can be moved from
one computer to another
one computer to another import
p j
java.io.FileOutStream;
import java.io.IOException;
– These files can then be read by a Java program, but only by
a Java program
Some Methods in the Class Some Methods in the Class
ObjectOutputStream (Part 1 of 5) ObjectOutputStream (Part 2 of 5)
Some Methods in the Class
Reading Simple Data from a Binary File
Reading Simple Data from a Binary File
ObjectOutputStream (Part 5 of 5)
• Th
The class ObjectInputStream
l Obj tI tSt i
is a stream class that can
t l th t
be used to read from a binary file
– An
An object of this class has methods to read strings, values of primitive
object of this class has methods to read strings, values of primitive
types, and objects from a binary file
• A program using ObjectInputStream needs to import
several classes from package java io:
several classes from package java.io:
import java.io.ObjectInputStream;
import
p j
java.io.FileInputStream;
p
import java.io.IOException;
Some Methods in the Class ObjectInputStream Some Methods in the Class ObjectInputStream
(Part 1 of 5) (Part 2 of 5)
Some Methods in the Class ObjectInputStream Checking for the End of a Binary File the Correct
(Part 5 of 5) Way
• All
All of the ObjectInputStream
f th Obj tI tSt methods that
th d th t
read from a binary file throw an EOFException
when trying to read beyond the end of a file
when trying to read beyond the end of a file
– This can be used to end a loop that reads all the data in a
file
• Note that different file‐reading methods check for
h d ff fl d h d h kf
the end of a file in different ways
– Testing
Testing for the end of a file in the wrong way can cause a
for the end of a file in the wrong way can cause a
program to go into an infinite loop or terminate
abnormally
• The streams for sequential access to files are
h f i l fil • Th
The stream class RandomAccessFile, which is in the
t l R d A Fil hi h i i th
java.io package, provides both read and write random
the ones most commonly used for file access access to a file in Java
in Java • A random access file consists of a sequence of numbered
• However, some applications require very rapid
, pp q y p bytes
– There is a kind of marker called the file pointer that is always
access to records in very large databases positioned at one of the bytes
– These applications need to have random access to
These applications need to have random access to – All reads and writes take place starting at the file pointer location
p g f p
particular parts of a file – The file pointer can be moved to a new location with the method
seek
Some Methods of the Class RandomAccessFile Some Methods of the Class RandomAccessFile
(P t 2 f 7)
(Part 2 of 7) (P t 3 f 7)
(Part 3 of 7)
Some Methods of the Class RandomAccessFile Some Methods of the Class RandomAccessFile
(P t 6 f 7)
(Part 6 of 7) (P t 7 f 7)
(Part 7 of 7)