Java Tutorial/File/Introduction

Материал из Java эксперт
Версия от 17:44, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Input Output

There are four types of streams: InputStream, OutputStream, Reader, and Writer.

  1. Reader. A stream to read characters.
  2. Writer. A stream to write characters.
  3. InputStream. A stream to read binary data.
  4. OutputStream. A stream to write binary data.

For better performance, use the buffered I/O classes: BufferedInputStream, BufferedOutputStream, BufferedReader, and BufferedWriter.

Reading from and writing to a stream dictate that you do so sequentially. The java.io.RandomAccessFile is for non-sequential operations.

For object serialization and deserialization, you can use the ObjectInputStream and ObjectOutputStream classes.


OutputStream

The OutputStream class defines three write method overloads, which are mirrors of the read method overloads in InputStream:



public void write (int b)
public void write (byte[] data)
public void write (byte[] data, int offset, int length)



  1. The first overload writes the lowest 8 bits of the integer b to this OutputStream.
  2. The second writes the content of a byte array to this OutputStream.
  3. The third overload writes length bytes of the data starting at offset offset.
  1. close() method closes the OutputStream.
  2. flush() method forces any buffered content to be written out to the sink.


Reading Binary Data

You use an InputStream to read binary data.



InputStream
  |
  +-- FileInputStream 
  |
  +-- BufferedInputStream



  1. FileInputStream enables easy reading from a file.
  2. BufferedInputStream provides data buffering that improves performance.
  3. The ObjectInputStream class is used in object serialization.


Writing Binary Data

The OutputStream abstract class represents a stream for writing binary data



OutputStream
  |
  +--FileOutputStream
  |
  +--BufferedOutputStream. 
  |
  +--ObjectOutputStream



  1. FileOutputStream provides a convenient way to write to a file.
  2. BufferedOutputStream provides better performance.
  3. ObjectOutputStream class plays an important role in object serialization.