Home > Java > Picking the right IO class

Picking the right IO class

May 8th, 2009

Choosing the right class for IO is not always obvious. Java offers several levels of abstraction.

At the most basic level are streams of bytes. That is raw data. There is two kind of streams, input and output streams. There are two major resource kind, files and byte arrays. (We will come back on that below, when we talk about testing.)

new FileInputStream(filename);
new ByteArrayInputStream(bytes);
new FileOutputStream(filename);
new ByteArrayOutputStream();

To get the result of a byte array output stream, call its #toString method.

If you work with text, you should use readers and writers. They know how to encode characters as bytes and vice versa. There are different character encodings, of which ISO-8859-1 and UTF-8 are the most important. Whenever possible you should use UTF-8.

To create a reader, wrap it around an input stream. To create a writer, wrap it around an output stream.

new InputStreamReader(new FileInputStream(filename), "UTF-8");
new InputStreamReader(new ByteArrayInputStream(bytes), "UTF-8");
new OutputStreamWriter(FileOutputStream(filename), "UTF-8");
new OutputStreamWriter(ByteArrayOutputStream(), "UTF-8");

Plus there are two special classes to work with strings.

new StringReader(string);
new StringWriter();

To get the result of a string writer, just call its #toString method.

If you write to a file all characters are immediately written to disk. This is slow. It’s much faster to first write to a buffer, and only flush its content to disk when to buffer is full. The same applies for reading. Therefore, there are additional wrappers that buffer the underlying stream.

new BufferedReader(new InputStreamReader(stream));
new BufferedWriter(new OutputStreamWriter(stream));

If you work with binary data, you can either use a random access file or one of data input and data output stream. Random access files are called random access file, because they dont stream over the file but always provide access to any position within the file. Like a chunk of memory.

new RandomAccessFile(filename);
new DataInputStream(stream);
new DataOutputStream(stream);

(Random access file are a rather modern invention, for example my very first computer still used a tape as disk – yes the same as your beloved Kasperlikasette – and thus random access was technically impossible. Plus no harddisk, no mouse, no graphical user interface, no file system, no color screen, just 320 on 200 monochrome pixels, 1 Mhz slow, and only 64k memory. But lots of fun.)

How to test file access?

Typically your program will read and write to files. However, tests should not creates files but rather work in-memory only. This can be done using the byte array streams instead of the files streams.

akuhn Java

Comments are closed.