IO Handling in Java

1. Stream:

  • Sequence of Bytes
  • Flow of Bytes

2. A stream can be compared to a pipe. It has two main parts: Input Stream and Output Stream.

3. Files are the collection of related information.

4. A file is opened in several ways:

  • Input
  • Output
  • Append

Adding something to the file is known as appending the file.

5. Text files are human readable and binary files are not human readable.

6. In Java IO is of two types:

  • Byte Oriented (byte stream or binary files)
  • Character Oriented (text files or character stream)

7. Character Stream was not present in JDK 1.0 

8. While working with byte stream there will be no automatic buffering and in case of a character stream, there will be automatic buffering.

9. Character Stream is preferred over byte stream as Internationalization is easy in character stream and automatic translation depends upon the locale. It is based on UNICODE.

In byte stream: InputStream and OutputStream is associated with every name convention of class as in character stream we have Writer and Reader.

Example:
Byte Stream : DataInputStream, FileInputStream, ObjectInputStream, ObjectOutputStream, DataOutputStream, FileOutputStream, etc.
Character Stream: PrintWriter, FileWriter, FileReader, BufferedReader,  etc.

Example 1: input.java (As byte stream)

import java.io.*;
class Input{
public static void main(String[] args){
     DataInputStream dis=new DataInputStream(System.in);
     System.out.println(“Enter a number);
     int num=Integer.parseInt(dis.readLine());
     System.out.println(num+10);
}
}

Note:

1. Save the program as input.java
2. Compile the program: javac input.java
3. Now run the compiled file: java Input

Example 2: input2.java (as character stream)

import java.io.*;
class Input2{
public static void main(String[] args){
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     System.out.println(“Enter a number);
     String str=br.readLine();
     int num=Integer.parseInt(str);
     System.out.println(num+10);
}
}

Note:

1. Save the program as input2.java
2. Compile the program: javac input2.jav
3. Now run the compiled file: java Input2