Java Reference
In-Depth Information
Program P7.3
import java.io.*;
public class ReadBinaryFile {
public static void main(String[] args) throws IOException {
DataInputStream in = new DataInputStream(new FileInputStream("num.bin"));
int amt = 0;
try {
while (true) {
int n = in.readInt();
System.out.printf("%d ", n);
++amt;
}
}
catch (IOException e) { }
System.out.printf("\n\n%d numbers were read\n", amt);
} //end main
} //end class ReadBinaryFile
If num.bin contains the output from Program P7.2, then Program P7.3 produces the following output:
25 18 47 96 73 89 82 13 39
9 numbers were read
The new statement in Program P7.3 is this:
DataInputStream in = new DataInputStream(new FileInputStream("num.bin"));
A data input stream lets a program read primitive Java data types from an input stream that was created as a data
output stream. A file input stream is an input stream for reading data from a file. The following constructor creates an
input stream connected to the file num.bin :
new FileInputStream("num.bin")
The following are some of the methods in the DataInputStream class:
int readInt() //read 4 input bytes and return an int value
double readDouble() //read 8 input bytes and return a double value
char readChar() //read a char as a 2-byte value
void readFully(byte[] b) //read bytes and store in b until b is full
float readFloat() //read 4 input bytes and return a float value
long readLong() //read 8 input bytes and return a long value
int skipBytes(int n) //attempts to skip n bytes of data;
//returns the number actually skipped
Generally speaking, these methods are used to read data that was written using the corresponding “write”
methods from DataOutputStream .
Note the use of try...catch to read numbers until end-of-file is reached. Recall that there is no “end-of-data”
value in the file, so we can't test for this. The while statement will read from the file continuously. When the end-of-
file is reached, an EOFException is thrown. This is a subclass of IOException and so is caught.
The catch block is empty, so nothing happens there. Control goes to the following statement, which prints the
amount of numbers read.
Search WWH ::




Custom Search