站内搜索: 请输入搜索关键词
当前页面: 在线文档首页 > Java Tutorial 5.0 英文版

Questions and Exercises: I/O: Reading and Writing - Java Tutorial 5.0 英文版

The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Essential Java Classes
Lesson: I/O

Questions and Exercises: I/O: Reading and Writing

Questions

1. What class would you use to read a few pieces of data that are at known positions near the end of a large file?

2. What class in the java.util.zip (in the API reference documentation) package gives you access to the entries in a ZIP archive and allows you to read those entries through a stream?

3. How would you append data to the end of a file? Show the constructor for the class you would use and explain your answer.

4. How can you improve the performance of the following code? Explain your answer and show the new line(s) of code.

int i;
URL url = new URL("http://java.sun.com/");
URLConnection javaSite = url.openConnection();
InputStream input = javaSite.getInputStream();
InputStreamReader reader = new InputStreamReader(input);
while ((i = reader.read()) != -1) {
    System.out.print(i);
}

Exercises

1. Modify the program discussed in the section How to Use Pipe Streams (in the Essential Java Classes trail) so that it uses input streams and output streams in place of readers and writers.

2. Implement a pair of classes, one Reader and one Writer, that count the number of times a particular character, such as e, is read or written. The character can be specified when the stream is created. Write a program to test your classes. You can use farrago.txt (in a .java source file) as the input file.

3. The file datafile (in a .java source file) begins with a single long that tells you the offset of a single int piece of data within the same file. Using the RandomAccessFile class, write a program that gets the int piece of data. What is the int data?

4. In this exercise, you'll implement object serialization for the Card2 (in a .java source file) class.

a. Rename the class Card3 and make it serializable.

b. Create a program named CardWriter that creates a Card3 instance, displays its value, and serializes it into a file named card.out. Here is an example of what CardWriter might display:

      Card to write is: Ace of Spades

c. Create a program named CardReader that reads the Card3 object from card.out and displays its value. For example:

      Card read is: Ace of Spades


Check your answers. (in the Essential Java Classes trail)
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.