Java Reference
In-Depth Information
Program P7.2
import java.io.*;
import java.util.*;
public class CreateBinaryFile {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new FileReader("num.txt"));
DataOutputStream out = new DataOutputStream(new FileOutputStream("num.bin"));
int n = in.nextInt();
while (n != 0) {
out.writeInt(n);
n = in.nextInt();
}
out.close();
in.close();
} //end main
} //end class CreateBinaryFile
Suppose num.txt contains the following:
25 18 47 96 73 89 82 13 39 0
When Program P7.2 is run, the numbers (except 0 ) will be stored in their internal form in the file, num.bin .
The new statement in Program P7.2 is this:
DataOutputStream out = new DataOutputStream(new FileOutputStream("num.bin"));
A data output stream lets a program write primitive Java data types to an output stream. A file output stream is an
output stream for writing data to a file. The following constructor creates an output stream connected to the file num.bin :
new FileOutputStream("num.bin")
The following are some of the methods in the DataOutputStream class. All methods write to the underlying
output stream, and all values are written with the high byte first (that is, from most significant to least significant byte).
void writeInt(int v) //write an int
void writeDouble(double v) //write a double value
void writeChar(int v) //write a char as a 2-byte value
void writeChars(String s) //write a string as a sequence of chars
void writeFloat(float v) //write a float value
void writeLong(long v) //write a long value
void write(int b) //write the low 8-bits of b
In Program P7.2, out.writeInt(n) writes the integer n to the file num.bin . If you try to view the contents of num.
bin , all you would see is nonsense. Only a program can read and make sense of what is in the file.
Consider Program P7.3, which reads the numbers from the file num.bin and prints them.
Search WWH ::




Custom Search