Why does Java define both byte and character streams?
The byte streams are the original streams defined by Java. They are especially useful for binary I/O, and they support random-access files. The character streams are optimized for Unicode.
Even though console input and output is text-based, why does Java still use byte streams for this purpose?
The predefined streams, System.in
, System.out
, and System.err
, were defined before Java added the character streams.
Show how to open a file for reading bytes.
Here is one way to open a file for byte
input:
FileInputStream fin = new FileInputStream("test")
Show how to open a file for reading characters.
Here is one way to open a file for reading characters:
FileReader fr = new FileReader("test");
Show how to open a file for random-access I/O.
Here is one way to open a file for random access:
randFile = new RandomAccessFile("test", "rw");
How can you convert a numeric string such as "123.23" into its binary equivalent?
To convert numeric strings into their binary equivalents, use the parsing methods defined by the type wrappers, such as Integer
or Double
.
Write a program that copies a text file. In the process, have it convert all spaces into hyphens. Use the byte stream file classes. Use the traditional approach to closing a file by explicitly calling close()
.
$ java Hyphen file1.txt file2.txt
Rewrite the program described in question 7 so that it uses the character stream classes. This time, use the try
-with-resources statement to automatically close the file.
$ java Hyphen file1.txt file2.txt
What type of stream is System.in
?
InputStream
What does the read()
method of InputStream
return when an attempt is made to read at the end of the stream?
-1
What type of stream is used to read binary data?
DataInputStream
Reader
and Writer
are at the top of the ____________ class hierarchies.
Character-based I/O.
The try
-with-resources statement is used for ___________________________________.
Automatic resource management.
If you are using the traditional method of closing a file, then closing a file within a finally
block is generally a good approach. True or False?
True.
Can local variable type inference be used when declaring the resource in a try
-with-resources statement?
Yes.