Unit 14 : Input/output:

3rd Semester

Java I/O
 A stream is continuous group of data or a channel through which data flows from one point to
another point.
 Java implements streams within class hierarchies defined in the java.io package.
 Byte streams provide a convenient means for handling input and output of bytes. Byte streams
are used, for example, when reading or writing binary data.
 Character streams provide a convenient means for handling input and output of characters.
They use Unicode and, therefore, can be internationalized. Also, in some cases, character
streams are more efficient than byte streams.
Stream
Java programs perform I/O through streams. A stream is an abstraction that either produces or
consumes information. A stream is linked to a physical device by the Java I/O system. All streams
behave in the same manner, even if the actual physical devices to which they are linked differ. Thus, the
same I/O classes and methods can be applied to any type of device. This means that an input stream
can abstract many different kinds of input: from a disk file, a keyboard, or a network socket. Likewise,
an output stream may refer to the console, a disk file, or a network connection. Streams are a clean way
to deal with input/output without having every part of your code understands the difference between a
keyboard and a network, for example. Java implements streams within class hierarchies defined in the
java.io package. Java 2 defines two types of streams: byte and character
Byte streams provide a convenient means for handling input and output of bytes. Byte streams are
used, for example, when reading or writing binary data. Character streams provide a convenient
means for handling input and output of characters. They use Unicode and, therefore, can be
internationalized. Also, in some cases, character streams are more efficient than byte streams.
The Byte Stream Classes
 Byte streams are defined by using two class hierarchies. At the top are two abstract classes:
InputStream and OutputStream.
 To use the stream classes, we must import java.io.
 The abstract classes InputStream and OutputStream define several key methods that the
other stream classes implement.
 Two of the most important are read ( ) and write ( ), which, respectively, read and write bytes of
data. Both methods are declared as abstract inside InputStream and OutputStream. They are
overridden by derived stream classes.
The Character Stream Classes
 Character streams are defined by using two class hierarchies. At the top are two abstract
classes, Reader and Writer. These abstract classes handle Unicode character streams. Java has
several concrete subclasses of each of these.
 The abstract classes Reader and Writer define several key methods that the other stream
classes implement. Two of the most important methods are read ( ) and write ( ), which read
and write characters of data, respectively. These methods are overridden by derived stream
classes.
Java System Class
 All Java programs automatically import the java.lang package.
 This package defines a class called System, which encapsulates several aspects of the run-time
environment.
 System also contains three predefined stream variables, in, out, and err. These fields are
declared as public and static within System. This means that they can be used by any other
part of your program and without reference to a specific System object.
 System.out refers to the standard output stream. By default, this is the console.
 System.in refers to standard input, which is the keyboard by default.
 System.err refers to the standard error stream, which also is the console by default.
 System.in is an object of type InputStream; System.out and System.err are objects of type
PrintStream. These are byte streams, even though they typically are used to read and write
characters from and to the console.
Reading Console Input
In Java, console input is accomplished by reading from System.in. To obtain a character-based stream
that is attached to the console, you wrap System.in in a BufferedReader object, to create a character
stream. BuffereredReader supports a buffered input stream. Its most commonly used constructor is
shown here:
BufferedReader(Reader inputReader)
Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created.
Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes
to characters. To obtain an InputStreamReader object that is linked to System.in, use the following
constructor:
InputStreamReader(InputStream inputStream)
Because System.in refers to an object of type InputStream, it can be used for inputStream. Putting it
all together, the following line of code creates a BufferedReader that is connected to the keyboard:
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
After this statement executes, br is a character-based stream that is linked to the console through
System.in.
Reading Characters
To read a character from a BufferedReader, use read( ). The version of read( ) that we will be using is
int read( ) throws IOException Each time that read( ) is called, it reads a character from the input stream
and returns it as an integer value. It returns –1 when the end of the stream is encountered.
Reading Strings
To read a string from the keyboard, use the version of readLine( ) that is a member of the
BufferedReader class. Its general form is shown here:
String readLine( ) throws IOException
Write a program to find addition of two numbers given from the keyboard. Using
exception handling, display appropriate message if the inputs are not valid numbers.
Solution:
import java.io.*;
class Addition
{
public static void main(String args[])
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
int x, y, z;
try
{
System.out.println(“Enter 1st number”);
str = br.readLine();
x=Integer.parseInt(str);
System.out.println(“Enter 2nd number”);
str = br.readLine();
y=Integer.parseInt(str);
z=x+y;
System.out.print(“Addition Result is: ”+z);
}
catch (Exception e)
{
System.out.println(“Invalid Number ..Try Again!!!!!!!”);
}
}
}
Write a program to find factorial of an integer given from the keyboard. Using
exception handling mechanism, display appropriate message if the input from keyboard is not a
valid integer.
Solution:
import java.io.*;
class Factorial
{
public static void main(String args[])
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
int n, f=1, i;
try
{
System.out.println(“Enter the number”);
str = br.readLine();
n=Integer.parseInt(str);
for(i=1; i<=n; i++)
f=f*i;
System.out.print(“Factorial is: ”+f);
}
catch (Exception e)
{
System.out.println(“Invalid Input ..Try Again!!!!!!!”);
}
}
}
Serialization
Java provides a mechanism, called object serialization where an object can be represented as a
sequence of bytes that includes the object’s data as well as information about the object’s type and the
types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and deserialized that is,
the type information and bytes that represent the object and its data can be used to recreate the object
in memory.
Most impressive is that the entire process is JVM independent, meaning an object can be serialized on
one platform and deserialized on an entirely different platform.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the
methods for deserializing and serializing an object.
The ObjectOutputStream class contains many write methods for writing various data types, but one
method in particular stands out:
public final void writeObject(Object x) throws IOException
The above method serializes an Object and sends it to the output stream. Similarly, the
ObjectInputStream class contains the following method for deserializing an object:
public final Object readObject() throws IOException, ClassNotFoundException
This method retrieves the next Object out of the stream and deserializes it. The return value is Object,
so you will need to cast it to its appropriate data type.
Serializing an Object
The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program
instantiates an Employee object and serializes it to a file.
When the program is done executing, a file named employee.ser is created. The program does not
generate any output, but study the code and try to determine what the program is doing.
Note: When serializing an object to a file, the standard convention in Java is to give the file a .ser
extension.
Demonstration of object serialization.
Solution:
import java.io.*;
class Employee implements java.io.Serializable
{
public String name;
public String address;
public transient int age;
public int number;
public void mailCheck()
{
System.out.println(“Mailing a check to ” + name + ” ” + address);
}
}
public class SerializeDemo
{
public static void main(String [] args)
{
Employee e = new Employee();
e.name = “Sourav Kumar Giri”;
e.address = “Baleswar, Odisha.”;
e.age =25;
e.number = 101;
try
{
FileOutputStream fileOut =new FileOutputStream(“employee.ser”);
ObjectOutputStream out =new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
}
catch(IOException i)
{
i.printStackTrace();
}
}
}
Deserializing an Object
The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo
program. Study the program and try to determine its output:
Demonstration of object de-serialization.
Solution:
import java.io.*;
public class DeserializeDemo
{
public static void main(String [] args)
{
Employee e = null;
try
{
FileInputStream fileIn =new FileInputStream(“employee.ser”);
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}
catch(IOException i)
{
i.printStackTrace();
return;
}
catch(ClassNotFoundException c)
{
System.out.println(“Employee class not found”);
c.printStackTrace();
return;
}
System.out.println(“Deserialized Employee…”);
System.out.println(“Name: ” + e.name);
System.out.println(“Address: ” + e.address);
System.out.println(“Age ” + e.age);
System.out.println(“Number: ” + e.number);
}
}
Output: Deserialized Employee…
Name: Sourav Kumar Giri
Address: Baleswar, Odisha
Age: 0
Number:101
Here are following important points to be noted:
• The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject()
method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class.
If the JVM can’t find a class during the deserialization of an object, it throws a ClassNotFoundException.
• Notice that the return value of readObject() is cast to an Employee reference.
• The value of the age field was 25 when the object was serialized, but because the field is transient, this
value was not sent to the output stream. The age field of the deserialized Employee object is 0.

Assignments

Short Type Questions
1. Define Stream.
2. Differentiate between byte stream and character stream.
3. Define Serialization.
4. Differentiate between read() and readLine() in BufferedReader class.
Long Type Questions
1. Explain byte stream and character stream in java.
2. What is serialization in java? How to serialize and de-serialize an object in java? Explain with an
example.
3. Write a program to accept 3 numbers from the keyboard and display greatest among them. Use
exception handling for appropriate input (i.e. the inputs must be number only).
4. Write a program to accept a number from the keyboard and check whether the number is prime or
not