The JavaTM Tutorial

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form

Trail: Essential Java Classes
Lesson: I/O: Reading and Writing (but no 'rithmetic)

## Questions and Exercises: I/O: Reading and Writing (but no 'rithmetic)

### 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` 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. Suppose you wanted to write code that reads from a file one word at a time. The code needs to peek ahead to find where the words are separated by whitespace. What input stream could you use to accomplish this?

> 5. 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 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` as the input file.

> 3. The file `datafile` 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` 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.

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form

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