Table of Contents

Java - IO - Connection (Stream and Channel)

About

I/O - Stream in Java.

In order to perform I/O operations (for example reading or writing), you need to perform a connection.

In Java, this connection are modelled through:

They are classes (and methods) that opens connection to an entity such as:

that is capable of performing one or more distinct I/O operations, for example reading or writing.

A stream or channel can be seen as a sequential byte (read and write operations):

I/O Method

Java Fileiomethods

Stream Operations

Streams may be:

Architecture

All other stream types are built on the byte streams FileInputStream and FileOutputStream (reading/writing file one byte at a time) See Java - IO - Byte Stream

Byte

Java - IO - Byte Stream

Data Type

Characters

Java - IO - Character Stream

Java Primitive

Java Object

Filter

Filtered Streams = Transformation or More Functionalities on Streams.

A Filter(Input|Output)Stream uses (Input|Output) stream as its (source|target) of data:

The (superclass|abstract class) are:

Standard Stream

Java - IO - Standard Streams

Management Operations

Close

Closing a stream when it's no longer needed is very important.

The use of a finally block to guarantee that streams will be closed even if an error occurs and helps avoid serious resource leaks.

Copy:

try {
    in = new FileInputStream(Parameters.FILE_PATH_READ);
    out = new FileOutputStream(Parameters.FILE_PATH_WRITE);
    int c;

    while ((c = in.read()) != -1) {
        out.write(c);
    }
} finally {
    if (in != null) {
        in.close();
    }
    if (out != null) {
        out.close();
    }
}

One stream can be chained to another by passing it to the constructor of some second stream. When this second stream is closed, then it automatically closes the original underlying stream as well.

If multiple streams are chained together, then closing the one which was the last to be constructed, and is thus at the highest level of abstraction, will automatically close all the underlying streams. So, one only has to call close on one stream in order to close an entire series of related streams.

You should close the outermost OutputStream or Writer you have created from the socket output stream.

When a stream is closed, the connection between the stream and the entity (mostly a file) is canceled. After you have closed a stream, you cannot perform any additional operations on it.

Documentation / Reference