Java input output tutorial

In Java Input output operations are based on the concept of stream. The java.io package contains all the required classes to perform I/O operations.

A stream is defined as a sequence of data.

Automatically created streams in Java:

  1. System.in: the standard input stream.
  2. System.out: standard output stream.
  3. System.err: standard error.

Input stream:

InputStream is used to read data from a source like a file, peripheral device, etc.

InputStream class:

InputStream class is the superclass of all classes representing an input stream. It is an abstract class.

Commonly used methods of InputStream class:

1. read(): Reads the next byte of data from the input stream. It returns -1 at the end of the file.

Syntax: public abstract int read()throws IOException.

2. available(): Returns an estimate of the number of bytes that can be read from the current input stream.

Syntax: public int available()throws IOException.

3. close(): It is used to close the current input stream.

Syntax: public void close()throws IOException.

Output Stream:

OutputStream is used for writing data to a destination like a file, peripheral device, etc.

OutputStream class:

OutputStream class is the superclass of all classes representing an output stream. It is an abstract class.

Commonly used methods of OutputStream class:

1. write(int): This method is used to write a byte to the current output stream.

Syntax: public void write(int)throws IOException.

2. write(byte[]): This method is used to write an array of bytes to the current output stream.

Syntax: public void write(byte[])throws IOException.

3. flush(): flushes the current output stream.

Syntax: public void flush()throws IOException.

4. close(): This method is used to close the current output stream.

Syntax: public void close()throws IOException.

Java input output stream tutorial: