I/O Streams
Visit http://gsbprogramming.blogspot.in
In computer science, a stream is a sequence of data elements made available over time. A stream can be thought of
as items on a conveyor belt being processed one at a time rather than in large batches.
Streams are processed differently from batch data :
1. Normal functions cannot operate on streams as a whole, as they have potentially unlimited data, and
formally,
2. Streams are codata (potentially unlimited), not data (which is finite).
STREAMS
An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of
sources and destinations, including disk files, devices, other programs, and memory arrays.
Streams support many different kinds of data, including simple bytes, primitive data types, localized characters,
and objects. Some streams simply pass on data; others manipulate and transform the data in useful ways.
No matter how they work internally, all streams present the same simple model to programs that use them: A
stream is a sequence of data.
A program uses an input stream to read data from a source, one item at a time
A program uses an output stream to write data to a destination, one item at a time
I/O STREAMS
1. FileInputStream
2. DataInputStream
3. ObjectInputStream
4. SequenceInputStream
1. FileOutputStream
2. DataOutputStream
3. ObjectOutputStream
Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended
from InputStream and OutputStream.
1. FileReader
2. Buffered Reader
3. LineNumberReader
1. FileWriter
2. PrintWriter
A character stream will read a file character by character.The character streams are capable to read 16-bit characters
(byte streams read 8-bit characters). Character streams are capable to translate implicitly 8-bit data to 16-bit data or
vice versa. Character stream can support all types of character sets ASCII, Unicode, UTF-8, UTF-16 etc.But byte
stream is suitable only forASCII character set.
import java.io.*;
class A {
public static void main(String[] args) throws IOException {
FileInputStream fis = null;
int c;
try {
fis = new FileInputStream("D:BCD.txt");
while ((c = fis.read()) != -1) {
System.out.println("Value: " + c + " Character: " + (char) c);
}
}
finally{
if(fis !=null)
fis.close();
}
}
}
FileInputStream
Output:
Value: 65 Character: A
Value: 66 Character: B
Value: 67 Character: C
import java.io.*;
class CopyBytes {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("D:BCD.txt");
out = new FileOutputStream("D:XYZ.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null)
in.close();
if (out != null)
out.close();
}
}
}
FileOutputStream
//Write PrimitiveTypes to File
DataOutputStream dos = null;
try {
dos= new DataOutputStream(new FileOutputStream("D:Data.txt"));
dos.writeInt(10); dos.writeDouble(20.3);
dos.writeBoolean(true);
}
finally{
if(dos !=null) dos.close();
}
//Read PrimitiveTypes From File
DataInputStream dis = null;
try {
dis = new DataInputStream(new FileInputStream("D:Data.txt"));
System.out.println("Int: "+dis.readInt());
System.out.println("Double: "+dis.readDouble());
System.out.println("Boolean: "+dis.readBoolean());
}
finally{
if(dis !=null)
dis.close();
}
DataInputStream & DataOutputStream
Output:
Int: 10
Double: 20.3
Boolean: true
Serialization in Java
• 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 de-
serialized that is, the type information and bytes that represent the object and its data can
be used to recreate the object in memory.
• Serialization is a mechanism of converting the state of an object into a byte stream. De-
serialization is the reverse process where the byte stream is used to recreate the actual Java
object in memory.This mechanism is used to persist the object.
The byte stream created is platform independent. So, the object serialized on one platform can be
deserialized on a different platform
A Java object is serializable if its class or any of its super classes implements either
the java.io.Serializable interface or its sub interface, java.io.Externalizable.
Deserialization is the process of converting the serialized form of an object back into a copy of the object.
Serializable is a marker interface (has no data member and method). It is used to “mark” java classes so that
objects of these classes may get certain capability. Other examples of marker interfaces are:- Cloneable and
Remote.
Points to remember
1. If a parent class has implemented Serializable interface then child class doesn’t need to implement it but
vice-versa is not true.
2. Only non-static data members are saved via Serialization process.
3. Static data members and transient data members are not saved via Serialization process.So, if you don’t
want to save value of a non-static data member then make it transient.
4. Constructor of object is never called when an object is deserialized.
public class Employee implements java.io.Serializable
{
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck()
{
System.out.println("Mailing a check to " + name + " " + address);
}
}
import java.io.*;
public class SerializeDemo {
public static void main(String [] args) {
Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan,Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try {
FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
}catch(IOException i) {
i.printStackTrace();
}
}
}
Serialization in Java
import java.io.*;
public class DeserializeDemo {
public static void main(String [] args) {
Employee e = null;
try {
FileInputStream fileIn = new FileInputStream("/tmp/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("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}
De-Serialization in Java
Output
Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper
classes.
For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.
Here is the simplest example of autoboxing:
Character ch = 'a';
The automatic conversion of wrapper class type into corresponding primitive type, is known as Unboxing. Let's see the example of unboxing:
Integer i=new Integer(50);
int a=i;
Boxing and Un-Boxing in Java
//Used For Reading from multiple streams
FileInputStream input1 = new FileInputStream("D:A.txt");
FileInputStream input2 = new FileInputStream("D:B.txt");
SequenceInputStream inst = new SequenceInputStream(input1, input2);
int j;
while ((j = inst.read()) != -1) {
System.out.print((char) j);
}
inst.close();
input1.close();
input2.close();
SequenceInputStream
Output:
ABCXYZ
FileReader
import java.io.*;
class A {
public static void main(String[] args) throws IOException {
FileReader fr=new FileReader("D:A.txt");
int r;
while((r=fr.read())!=-1)
System.out.print((char)r);
fr.close();
}
}
Output:
ABC
BufferedReader
import java.io.*;
class A {
public static void main(String[] args) throws IOException {
FileReader fr=new FileReader("D:A.txt");
BufferedReader br= new BufferedReader(fw);
String s;
while ((s =br.readLine() !=null){
System.out.println(s);
}
fr.close();
br.close();
}
}
FileWriter
import java.io.*;
class A {
public static void main(String[] args) throws IOException {
FileWriter fw=new FileWriter("D:A.txt");
int r=65; //Character "A"
fw.write(r);
fw.close();
}
}
PrintWriter
import java.io.*;
class A {
public static void main(String[] args) throws IOException {
FileWriter fw=new FileWriter("D:A.txt");
PrintWriter pw=new PrintWriter(fw);
pw.println(“Hello”);
pw.close();
fw.close();
}
}
LineNumberReader
import java.io.*;
class A {
public static void main(String[] args) throws IOException {
LineNumberReader lnr=new LineNumberReader(new
FileReader("D:A.txt"));
System.out.println(lnr.getLineNumber());
System.out.println(lnr.readLine());
System.out.println(lnr.getLineNumber());
lnr.close();
}
Output:
0
Line1
1

IO Streams, Serialization, de-serialization, autoboxing

  • 1.
  • 2.
    In computer science,a stream is a sequence of data elements made available over time. A stream can be thought of as items on a conveyor belt being processed one at a time rather than in large batches. Streams are processed differently from batch data : 1. Normal functions cannot operate on streams as a whole, as they have potentially unlimited data, and formally, 2. Streams are codata (potentially unlimited), not data (which is finite). STREAMS
  • 3.
    An I/O Streamrepresents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays. Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects. Some streams simply pass on data; others manipulate and transform the data in useful ways. No matter how they work internally, all streams present the same simple model to programs that use them: A stream is a sequence of data. A program uses an input stream to read data from a source, one item at a time A program uses an output stream to write data to a destination, one item at a time I/O STREAMS
  • 4.
    1. FileInputStream 2. DataInputStream 3.ObjectInputStream 4. SequenceInputStream 1. FileOutputStream 2. DataOutputStream 3. ObjectOutputStream Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended from InputStream and OutputStream.
  • 5.
    1. FileReader 2. BufferedReader 3. LineNumberReader 1. FileWriter 2. PrintWriter A character stream will read a file character by character.The character streams are capable to read 16-bit characters (byte streams read 8-bit characters). Character streams are capable to translate implicitly 8-bit data to 16-bit data or vice versa. Character stream can support all types of character sets ASCII, Unicode, UTF-8, UTF-16 etc.But byte stream is suitable only forASCII character set.
  • 6.
    import java.io.*; class A{ public static void main(String[] args) throws IOException { FileInputStream fis = null; int c; try { fis = new FileInputStream("D:BCD.txt"); while ((c = fis.read()) != -1) { System.out.println("Value: " + c + " Character: " + (char) c); } } finally{ if(fis !=null) fis.close(); } } } FileInputStream Output: Value: 65 Character: A Value: 66 Character: B Value: 67 Character: C
  • 7.
    import java.io.*; class CopyBytes{ public static void main(String[] args) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("D:BCD.txt"); out = new FileOutputStream("D:XYZ.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) in.close(); if (out != null) out.close(); } } } FileOutputStream
  • 8.
    //Write PrimitiveTypes toFile DataOutputStream dos = null; try { dos= new DataOutputStream(new FileOutputStream("D:Data.txt")); dos.writeInt(10); dos.writeDouble(20.3); dos.writeBoolean(true); } finally{ if(dos !=null) dos.close(); } //Read PrimitiveTypes From File DataInputStream dis = null; try { dis = new DataInputStream(new FileInputStream("D:Data.txt")); System.out.println("Int: "+dis.readInt()); System.out.println("Double: "+dis.readDouble()); System.out.println("Boolean: "+dis.readBoolean()); } finally{ if(dis !=null) dis.close(); } DataInputStream & DataOutputStream Output: Int: 10 Double: 20.3 Boolean: true
  • 9.
    Serialization in Java •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 de- serialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory. • Serialization is a mechanism of converting the state of an object into a byte stream. De- serialization is the reverse process where the byte stream is used to recreate the actual Java object in memory.This mechanism is used to persist the object.
  • 10.
    The byte streamcreated is platform independent. So, the object serialized on one platform can be deserialized on a different platform
  • 11.
    A Java objectis serializable if its class or any of its super classes implements either the java.io.Serializable interface or its sub interface, java.io.Externalizable. Deserialization is the process of converting the serialized form of an object back into a copy of the object. Serializable is a marker interface (has no data member and method). It is used to “mark” java classes so that objects of these classes may get certain capability. Other examples of marker interfaces are:- Cloneable and Remote. Points to remember 1. If a parent class has implemented Serializable interface then child class doesn’t need to implement it but vice-versa is not true. 2. Only non-static data members are saved via Serialization process. 3. Static data members and transient data members are not saved via Serialization process.So, if you don’t want to save value of a non-static data member then make it transient. 4. Constructor of object is never called when an object is deserialized.
  • 12.
    public class Employeeimplements java.io.Serializable { public String name; public String address; public transient int SSN; public int number; public void mailCheck() { System.out.println("Mailing a check to " + name + " " + address); } }
  • 13.
    import java.io.*; public classSerializeDemo { public static void main(String [] args) { Employee e = new Employee(); e.name = "Reyan Ali"; e.address = "Phokka Kuan,Ambehta Peer"; e.SSN = 11122333; e.number = 101; try { FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(e); out.close(); fileOut.close(); System.out.printf("Serialized data is saved in /tmp/employee.ser"); }catch(IOException i) { i.printStackTrace(); } } } Serialization in Java
  • 14.
    import java.io.*; public classDeserializeDemo { public static void main(String [] args) { Employee e = null; try { FileInputStream fileIn = new FileInputStream("/tmp/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("SSN: " + e.SSN); System.out.println("Number: " + e.number); } } De-Serialization in Java Output Deserialized Employee... Name: Reyan Ali Address:Phokka Kuan, Ambehta Peer SSN: 0 Number:101
  • 15.
    Autoboxing is theautomatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing. Here is the simplest example of autoboxing: Character ch = 'a'; The automatic conversion of wrapper class type into corresponding primitive type, is known as Unboxing. Let's see the example of unboxing: Integer i=new Integer(50); int a=i; Boxing and Un-Boxing in Java
  • 16.
    //Used For Readingfrom multiple streams FileInputStream input1 = new FileInputStream("D:A.txt"); FileInputStream input2 = new FileInputStream("D:B.txt"); SequenceInputStream inst = new SequenceInputStream(input1, input2); int j; while ((j = inst.read()) != -1) { System.out.print((char) j); } inst.close(); input1.close(); input2.close(); SequenceInputStream Output: ABCXYZ
  • 17.
    FileReader import java.io.*; class A{ public static void main(String[] args) throws IOException { FileReader fr=new FileReader("D:A.txt"); int r; while((r=fr.read())!=-1) System.out.print((char)r); fr.close(); } } Output: ABC
  • 18.
    BufferedReader import java.io.*; class A{ public static void main(String[] args) throws IOException { FileReader fr=new FileReader("D:A.txt"); BufferedReader br= new BufferedReader(fw); String s; while ((s =br.readLine() !=null){ System.out.println(s); } fr.close(); br.close(); } }
  • 19.
    FileWriter import java.io.*; class A{ public static void main(String[] args) throws IOException { FileWriter fw=new FileWriter("D:A.txt"); int r=65; //Character "A" fw.write(r); fw.close(); } }
  • 20.
    PrintWriter import java.io.*; class A{ public static void main(String[] args) throws IOException { FileWriter fw=new FileWriter("D:A.txt"); PrintWriter pw=new PrintWriter(fw); pw.println(“Hello”); pw.close(); fw.close(); } }
  • 21.
    LineNumberReader import java.io.*; class A{ public static void main(String[] args) throws IOException { LineNumberReader lnr=new LineNumberReader(new FileReader("D:A.txt")); System.out.println(lnr.getLineNumber()); System.out.println(lnr.readLine()); System.out.println(lnr.getLineNumber()); lnr.close(); } Output: 0 Line1 1