Tuesday, December 4, 2007

Java File IO



“Bridge/Filter” classes: InputStreamReader (<-FileReader) converts an InputStream to a Reader and OutputStreamWriter (<-FileWriter) converts an OutputStream to a Writer.

- Two basic file format: binary vs ASCII
For example, integer 268
In binary representation, recall that in Java, integers are stored in 2's complement using 4 bytes of storage. Thus, 268 has the internal representation: 00000000 00000000 00000001 00001100
In ASCII representation, which would mean saving the ASCII code for the digits "2", "6", and "8". The code is


"2" = 50(10) = 00110010(2)
"6" = 54(10) = 00110110(2)
"8" = 56(10) = 00111000(2)

Thus, 268 would be written to the file as
00110010 00110110 00111000

The advantages of ACII Format
* ASCII text can be understood by any text editor.
* The file can be edited by hand if you wish to change information.
The disadvantages of ASCII Format
* Storing in ASCII requires first converting the number to ASCII
* In the above example, the ASCII version took less space (3 bytes vs 4 bytes). However, more typically, ASCII takes up more space and so your file will be bigger. For example, the number 10245 uses 5 bytes in ASCII rather than 4 in binary.
* ASCII only allows for 256 characters.

- Writing to an ASCII file using PrintWriter

File myFile = new File("DataFiles\\stuff.dat");

// Create an Output Stream
FileOutputStream outStream = new FileOutputStream(myFile);

// Filter bytes to ASCII
PrintWriter out = new PrintWriter(outStream);

// Here we actually write to file
out.println("Hello, this is a test.");
out.println(45);

// Reading from an ASCII file using BufferedReader
File myFile = new File("DataFiles\\stuff.dat");
// Create a Character Input Stream
// Note: FileReader inherits from InputStreamReader, which is a bridge from byte
// streams to character streams
FileReader inStream = new FileReader(myFile)

// Filter the Input Stream - buffers characters for efficiency
BufferedReader in = new BufferedReader(inStream);

String first = in.readLine();
String second = in.readLine();
if (second == null) System.out.println("End of file reached.");


See:
Thinking in Java / IO
File Input and Output

No comments: