Java Reference
In-Depth Information
As an alternative, you can wait for an
EOFException
(end-of-file exception) to be thrown
when a read method reaches the end of a stream. The loop that reads the data can be
enclosed in a
try
block, and the associated
catch
statement should handle only
EOFException
objects. You can call
close()
on the stream and take care of other
cleanup tasks inside the
catch
block.
This is demonstrated in the next project. Listings 15.5 and 15.6 contain two programs
that use data streams. The
PrimeWriter
application writes the first 400 prime numbers as
integers to a file called
400primes.dat
. The
PrimeReader
application reads the integers
from this file and displays them.
LISTING 15.5
The Full Text of
PrimeWriter.java
1: import java.io.*;
2:
3: public class PrimeWriter {
4: public static void main(String[] arguments) {
5: int[] primes = new int[400];
6: int numPrimes = 0;
7: // candidate: the number that might be prime
8: int candidate = 2;
9: while (numPrimes < 400) {
10: if (isPrime(candidate)) {
11: primes[numPrimes] = candidate;
12: numPrimes++;
13: }
14: candidate++;
15: }
16:
17: try {
18: // Write output to disk
19: FileOutputStream file = new
20: FileOutputStream(“400primes.dat”);
21: BufferedOutputStream buff = new
22: BufferedOutputStream(file);
23: DataOutputStream data = new
24: DataOutputStream(buff);
25:
26: for (int i = 0; i < 400; i++)
27: data.writeInt(primes[i]);
28: data.close();
29: } catch (IOException e) {
30: System.out.println(“Error — “ + e.toString());
31: }
32: }
33: