Java | I/O Streams

05 min read

I/O Streams:

  • Sequential & contiguous one-way flow of data
  • It is an abstract representation of input or output device that is a source or destination for data.

Java does not see any difference between different sources and sinks.The source/sink may be a disk file, network socket, standard I/0 devices like keyboard, monitor or even memory buffer. But the procedure for reading or writing data from and into these sources and sinks is the same.

  1. Byte oriented streams- handling i/p & o/p of bytes
  2. character-oriented streams- handling i/p & o/p of characters 

Why separate stream for characters?

Java internally stores characters in 16-bit UCS-2 character set format. But the external data source/sink could store characters in other character set formats such as UTF-8, UTF-16, US­-ASCII... Translations have to be done from UCS-2 to other charsets before storing character data in I/O devices. Similarly, while reading character data from I/0 devices, they should be converted from other charsets to UCS-2.

All stream classes have been defined in a java.io package. So, import this package.

 

1) Byte Oriented Streams:

The abstract classes InputStream and OutputStream define several methods that the other stream classes implement. Two of the most important are read() and write().

  • a) int read() reads a single byte and returns it as an integer. Returns -1 if the end of file is reached or read operation is not successful.
  • int read(byte[] buffer) reads an entire byte array
  • int read(byte[] buff, int offset, int n) reads the bytes into the array buff, starting from the position specified by offset and reads a total of 'n' characters.
  • void write(int b)
  • void write(byte[] buffer)
  • void write(byte[] buff, int offset, int n)

 

2) Character Oriented Systems:

The abstract classes Reader and Writer define several methods that the other stream classes implement. Two of the most important are read() and write().

  • int read() reads a single character and returns it as an integer. Returns -1 if the end of file is reached or read operation is not successful.
  • int read(char[] buffer) reads a char array
  • int read(char[] buff, int offset, int n) reads the characters into the array buff, starting from the position specified by offset and reads a total of (n' characters.
  • void write(int ch)
  • void write(char[] buffer)
  • void write(char[] buff, int offset, int n)
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error