Java Reference
In-Depth Information
If no buffer size is specified, the default size is
512
bytes. You can improve the perfor-
mance of the
TestDataStream
program in Listing 19.2 by adding buffers in the stream in
lines 6-7 and 21-22, as follows:
DataOutputStream output =
new
DataOutputStream(
(
new
FileOutputStream(
"temp.dat"
)));
DataInputStream input =
new
DataInputStream(
(
new
FileInputStream(
"temp.dat"
)));
new
BufferedOutputStream
new
BufferedInputStream
Tip
You should always use buffered I/O to speed up input and output. For small files, you
may not notice performance improvements. However, for large files—over 100 MB—you
will see substantial improvements using buffered I/O.
19.8
Why do you have to declare to throw
IOException
in the method or use a try-catch
block to handle
IOException
for Java I/O programs?
19.9
Why should you always close streams?
19.10
The
read()
method in
InputStream
reads a byte. Why does it return an
int
instead of a
byte
? Find the abstract methods in
InputStream
and
OutputStream
.
19.11
Does
FileInputStream
/
FileOutputStream
introduce any new methods beyond
the methods inherited from
InputStream
/
OutputStream
? How do you create a
FileInputStream
/
FileOutputStream
?
19.12
What will happen if you attempt to create an input stream on a nonexistent file? What
will happen if you attempt to create an output stream on an existing file? Can you
append data to an existing file?
19.13
How do you append data to an existing text file using
java.io.PrintWriter
?
19.14
Suppose a file contains an unspecified number of
double
values. Theses values were
written to the file using the
writeDouble
method using a
DataOutputStream
. How
do you write a program to read all these values? How do you detect the end of a file?
19.15
What is written to a file using
writeByte(91)
on a
FileOutputStream
?
19.16
How do you check the end of a file in an input stream (
FileInputStream
,
DataInputStream
)?
19.17
What is wrong in the following code?
✓
✓
Check
Point
import
java.io.*;
public class
Test {
public static void
main(String[] args) {
try
{
FileInputStream fis =
new
FileInputStream(
"test.dat"
);
}
catch
(IOException ex) {
ex.printStackTrace();
}
catch
(FileNotFoundException ex) {
ex.printStackTrace();
}
}
}
19.18
Suppose you run the program on Windows using the default ASCII encoding. After the
program is finished, how many bytes are in the file
t.txt
? Show the contents of each byte.