Using Streams in Java - Data Streams
(Page 4 of 4 )
If you need to work with data that isn't represented as bytes or characters, you can use data input and data output streams. These streams filter an existing byte stream so that each of the following primitive types can be read or written directly from the stream: boolean, byte, double, float, int, long, and short.
A data input stream is created with the DataInputStream(InputStream) constructor. The argument should be an existing input stream, such as a buffered input stream or a file input stream.
A data output stream requires the DataOutputStream(OutputStream) constructor, which indicates the associated output stream.
The following list indicates the read and write methods that apply to data input and output streams, respectively:
readBoolean(), writeBoolean(boolean)
readByte(), writeByte(integer)
readDouble(), writeDouble(double)
readFloat(), writeFloat(float)
readInt(), writeInt(int)
readLong(), writeLong(long)
readShort(), writeShort(int)
Each input method returns the primitive data type indicated by the name of the method. For example, the readFloat() method returns a float value.
There also are readUnsignedByte() and readUnsignedShort() methods that read in unsigned byte and short values. These are not data types supported by Java, so they are returned as int values.
Note - Unsigned bytes have values ranging from 0 to 255. This differs from Java's byte variable type, which ranges from –128 to 127. Along the same line, an unsigned short value ranges from 0 to 65,535, instead of the –32,768 to 32,767 range supported by Java's short type.
A data input stream's different read methods do not all return a value that can be used as an indicator that the end of the stream has been reached.
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 WritePrimes application writes the first 400 prime numbers as integers to a file called 400primes.dat. The ReadPrimes application reads the integers from this file and displays them.
Listing 15.5 The Full Text of WritePrimes.java
1: import java.io.*;
2:
3: public class WritePrimes {
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:
34: public static boolean isPrime(int checkNumber)
{
35: double root = Math.sqrt(checkNumber);
36: for (int i = 2; i <= root; i++) {
37: if (checkNumber % i == 0)
38: return false;
39: }
40: return true;
41: }
42: }
Listing 15.6 The Full Text of ReadPrimes.java
1: import java.io.*;
2:
3: public class ReadPrimes {
4: public static void main(String[] arguments) {
5: try {
6: FileInputStream file = new
7: FileInputStream("400primes.dat");
8: BufferedInputStream buff = new
9: BufferedInputStream(file);
10: DataInputStream data = new
11: DataInputStream(buff);
12:
13: try {
14: while (true) {
15: int in = data.readInt();
16: System.out.print(in + " ");
17: }
18: } catch (EOFException eof) {
19: buff.close();
20: }
21: } catch (IOException e) {
22: System.out.println("Error -- " +
e.toString());
23: }
24: }
25: }
Most of the WritePrimes application is taken up with logic to find the first 400 prime numbers. After you have an integer array containing the first 400 primes, it is written to a data output stream in lines 17–31.
This application is an example of using more than one filter on a stream. The stream is developed in a three-step process:
A file output stream associated with a file called 400primes.dat is created.
A new buffered output stream is associated with the file stream.
A new data output stream is associated with the buffered stream.
The writeInt () method of the data stream is used to write the primes to the file.
The ReadPrimes application is simpler because it doesn't need to do anything regarding prime numbers—it just reads integers from a file using a data input stream.
Lines 6–11 of ReadPrimes are nearly identical to statements in the WritePrimes application, except that input classes are used instead of output classes.
The try-catch block that handles EOFException objects is in lines 13–20. The work of loading the data takes place inside the try block.
The while(true) statement creates an endless loop. This isn't a problem; an EOFException automatically occurs when the end of the stream is encountered at some point as the data stream is being read. The readInt() method in line 15 reads integers from the stream.
The last several output lines of the ReadPrimes application should resemble the following:
2137 2141 2143 2153 2161 2179 2203 2207 2213 2221
2237 2239 2243 22
51 2267 2269 2273 2281 2287 2293 2297 2309 2311
2333 2339 2341 2347
2351 2357 2371 2377 2381 2383 2389 2393 2399 2411
2417 2423 2437 2
441 2447 2459 2467 2473 2477 2503 2521 2531 2539
2543 2549 2551 255
7 2579 2591 2593 2609 2617 2621 2633 2647 2657 2659
2663 2671 2677
2683 2687 2689 2693 2699 2707 2711 2713 2719 2729
2731 2741
Character Streams
After you know how to handle byte streams, you have most of the skills needed to handle character streams as well. Character streams are used to work with any text represented by the ASCII character set or Unicode, an international character set that includes ASCII.
Examples of files that you can work with through a character stream are plain text files, HTML documents, and Java source files.
The classes used to read and write these streams are all subclasses of Reader and Writer. These should be used for all text input instead of dealing directly with byte streams.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
|
This article is excerpted from chapter 15 of Sams Teach Yourself Java 2 in 21 Days, written by Rogers Cadenhead and Laura Lemay (Sams; ISBN: 0672326280). Check it out today at your favorite bookstore. Buy this book now.
|
|