Monday, November 1, 2010

CoolTuts - Java - IO

1. Data in files on your system is called persistent data, because it persists after the program runs.
2. Files are created through streams in Java Code
3. A stream is a linear sequential flow of bytes of input and output data.
4. Streams are written to the file system to create files
5. Streams can also be transferred over the internet.
6. There are three types of streams
System.out -- Standard Output Stream -- Standard Input Stream
System.err -- Standard Error package contains large number of classes that deal with Java input and output. Most of the classes consists of
  1. Byte Streams that are subclasses of InputStream and OutputStream
  2. Character streams that are subclasses of Reader and Writer

Reader and Writer classes read and write 16-bit Unicode characters. InputStream reads 8-bit bytes, while OutputStream writes 8-bit bytes.

If you use binary data, such as integers or doubles, then use the InputStream and OutputStream classes.
If you are using text data, then Reader and Writer classes are right.

Random Access

RandomAccessFile class permits random access. The data is stored in binary format. Using random access files improves performance and efficiency.

Object or Non-Object

If the data itself is an object, then use the ObjectInputStream and ObjectOutputStream classes.

Sources and sinks for data

You can Input or Output your data in number of ways: sockets, files, strings and arrays of characters.

Any of these can be a source for an InputStream or Reader or sink for an OutputStream or Writer.


Buffering Instead of going back to operating system for each byte, you can use an object to provide a buffer.

Checksumming As you are reading or writing a stream, you might want to compute a checksum on it. A checksum is a value you can use later to make sure the stream was transmitted properly.

InputStream classes

In the InputStream class, bytes can be read from three different sources:
1. An array of bytes
2. A file
3. A pipe

Input Stream Methods

1. abstract int read() reads a single byte, an array, or a subarray of bytes. It returns the bytes read, the number of bytes read, or -1 if end-of-file has been reached.
2. read(), which takes the byte array, reads an array or a subarray of bytes and returns a -1 if the end-of-file has been reached.
3. skip(), which takes long, skips a specified number of bytes of input and returns the number of bytes actually skipped.
4. available() returns the number of bytes that can be read without blocking. Both the input and output can block threads until the byte is read or written.
5. close() closes the input stream to free up system resources.

No comments:

Post a Comment