jump to navigation

File Handling and Input/Output August 5, 2005

Posted by Coolguy in J2SE.
trackback
  • To bring in information, a program opens a stream on an information source (a file, memory, a socket) and reads the information sequentially
  • Similarly, a program can send information to an external destination by opening a stream to a destination and writing the information out sequentially
  • The java.io package contains a collection of stream classes that support these algorithms for reading and writing.
  • The stream classes are divided into two class hierarchies, based on the data type (either characters or bytes) on which they operate
  • Character Streams
  • Byte Streams

Character Streams

  • Reader and Writer are the abstract superclasses for character streams
  • Character Streams read/write 16-bit characters and can handle any character in the Unicode character set
  • Subclasses of Reader and Writer implement specialized streams and are divided into two categories
  • Firstly those that read from or write to data sinks ~ shown in gray
  • Second those that perform some sort of processing ~ shown in white

Byte Streams

  • To read and write 8-bit bytes, programs should use the byte streams, descendants of InputStream and OutputStream.
  • These streams are typically used to read and write binary data such as images and sounds
  • Two of the byte stream classes, ObjectInputStream and ObjectOutputStream, are used for object serialization
  • Subclasses of InputStream and OutputStream provide specialized I/O that falls into two categories
  • Data sink streams (shaded)
  • Processing streams (unshaded)

Using the Streams

Type of I/O Streams Description
Memory

CharArrayReader
CharArrayWriter

ByteArrayInputStream
ByteArrayOutputStream

Use these streams to read from and write to memory. You create these streams on an existing array and then use the read and write methods to read from or write to the array.

StringReader
StringWriter

StringBufferInputStream

Use StringReader to read characters from a String in memory. Use StringWriter to write to a String. StringWriter collects the characters written to it in a StringBuffer, which can then be converted to a String.

StringBufferInputStream is similar to StringReader, except that it reads bytes from a StringBuffer.

Pipe

PipedReader
PipedWriter

PipedInputStream
PipedOutputStream

Implement the input and output components of a pipe. Pipes are used to channel the output from one thread into the input of another.

File

FileReader
FileWriter

FileInputStream
FileOutputStream

Collectively called file streams, these streams are used to read from or write to a file on the native file system.

Concatenation

N/A

SequenceInputStream

Concatenates multiple input streams into one input stream.

Object
Serialization

N/A

ObjectInputStream
ObjectOutputStream

Used to serialize objects.

Data
Conversion

N/A

DataInputStream
DataOutputStream

Read or write primitive data types in a machine-independent format.

Counting

LineNumberReader

LineNumberInputStream

Keeps track of line numbers while reading.

Peeking Ahead

PushbackReader

PushbackInputStream

These input streams each have a pushback buffer. When reading data from a stream, it is sometimes useful to peek at the next few bytes or characters in the stream to decide what to do next.

Printing

PrintWriter

PrintStream

Contain convenient printing methods. These are the easiest streams to write to, so you will often see other writable streams wrapped in one of these.

Buffering

BufferedReader
BufferedWriter

BufferedInputStream
BufferedOutputStream

Buffer data while reading or writing, thereby reducing the number of accesses required on the original data source. Buffered streams are typically more efficient than similar nonbuffered streams and are often used with other streams.

Filtering

FilterReader
FilterWriter

FilterInputStream
FilterOutputStream

These abstract classes define the interface for filter streams, which filter data as it’s being read or written.

Converting between Bytes and Characters

InputStreamReader
OutputStreamWriter

A reader and writer pair that forms the bridge between byte streams and character streams.

An InputStreamReader reads bytes from an InputStream and converts them to characters, using the default character encoding or a character encoding specified by name.

An OutputStreamWriter converts characters to bytes, using the default character encoding or a character encoding specified by name and then writes those bytes to an OutputStream.

You can get the name of the default character encoding by calling System.getProperty("file.encoding").

Using File Streams

  • E.g:
  • File inputFile = new File(“farrago.txt”);
  • FileReader in = new FileReader(inputFile);
  • FileWriter out = new FileWriter(outputFile);

Using Pipe Streams

  • Pipes are used to channel the output from one thread into the input of another.

Using Filter Streams

  • A filter stream filters data as it’s being read from or written to the stream
  • A filter stream is constructed on another stream (the underlying stream)
  • E.g:

BufferedReader d = new BufferedReader(new DataInputStream(System.in));

Serializing Objects

  • ObjectOutputStream, ObjectInputStream must be constructed on another stream
  • The objects must be read from the stream in the same order in which they were written
  • Writing

FileOutputStream out = new FileOutputStream(“theTime”);

ObjectOutputStream s = new ObjectOutputStream(out);

s.writeObject(“Today”);

s.writeObject(new Date());

s.flush();

  • Reading

FileInputStream in = new FileInputStream(“theTime”);

ObjectInputStream s = new ObjectInputStream(in);S

String today = (String)s.readObject();

Date date = (Date)s.readObject();

  • The return value from read Object is an object that is cast to and assigned to a specific type.
  • An object is serializable only if its class implements the Serializable interface.
  • The serialization of instances of the class implementing Serializable interface are handled by the defaultWriteObject method of ObjectOutputStream
  • You can customize serialization for your classes by providing two methods for it: writeObject and readObject
  • For complete, explicit control of the serialization process, a class must implement the Externalizable interface.
  • For Externalizable objects, only the identity of the object’s class is automatically saved by the stream. The class is responsible for writing and reading its contents, and it must coordinate with its superclasses to do so.

Random Access Files

  • The RandomAccessFile class in the java.io package implements a random access file
  • E:g: new RandomAccessFile(“farrago.txt”, “r”);
  • RandomAccessFile supports the notion of a file pointer. The file pointer indicates the current location in the file. When the file is first created, the file pointer is set to 0, indicating the beginning of the file. Calls to the read and write methods adjust the file pointer by the number of bytes read or written.
Advertisements

Comments»

No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: