Flat Preloader Icon

Java I/O

Overview

  • Input/Output Streams
  • Byte Oriented Streams
  • Character Oriented Streams
  • Object Serialization
  • Channel Based I/O

Input/Output Streams

  • Stream is an abstraction and can be thought of as flow of data from source to sink.
  • Source or InputStream initiates the flow of data.
  • Sink or OutputStream terminates the flow of data.
  • There is no concept of index like array in stream. It is just the flow of data.
  • Two types of Streams: Byte & Character Based
  • Standard Input and Output:
    • System.in is an InputStream representing standard input (usually the keyboard).
    • System.out is a PrintStream representing standard output (usually the console).
    • System.err is also a PrintStream representing standard error output.

    Byte Oriented Stream

    • InputStream class is used for reading the data in terms of bytes.
    • Some of the methods are read(), read(byte[]), read(byte[],int,int), close() etc.
    • OutputStream class is used for representing the output stream of data.
    • Some of the methods are write(int), write(byte[]), write(byte[], int,int), close() etc.
    • Demo

    Character Oriented Stream

    • Reader and Writer classes & their sub-classes are used for dealing with the characters.
    • read() and print() methods are used by these to read and write respectively.
    • BufferedReader and BufferedWriter classes provide the built-in buffer for reading and writing the data.
    • readLine() and write() are some methods used for reading and writing data by these classes.
    • Demo

    Serializing Objects

    • Serialization of objects is needed in case one wants to persist the objects in the permanent storage.
    • For reading & writing an object in a file, it should implement the Serializable interface.
    • ObjectInputStream & ObjectOutputStream are used to read & write the objects to a file.
    • They make use of witeObject & readObject methods, along with readXXX & writeXXX methods for the primitives.

    File I/O

    • Java provides classes like File, FileInputStream, FileOutputStream, FileReader, and FileWriter for file I/O operations.
    • To read from a file:
    				
    					try (FileInputStream fis = new FileInputStream
    ("file.txt")) {
        int data;
        while ((data = fis.read()) != -1) {
            // Process data
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    				
    			

    Channel Based I/O

    • Java Channels are similar to the Streams, with few differences:-
      • We can both read and write to a channel.
      • These are always read from/written to a buffer.
      • These can be read and written asynchronously.
    • Buffers are block of memory closely coupled with the underlying operating system.These too like arrays are of fixed capacity.
    • Data can be read/written into a buffer and these are used when interacting with channels.
    • Demo