Input and Output in Java
Input and Output in Java
Stream:
A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream because it's like a stream of water that continues to flow.
Do You Know ?
How to write a common data to multiple files using single stream only ? How can we access multiple files by single stream ? How can we improve the performance of Input and Output operation ? How many ways can we read data from the keyboard? What is console class ? How to compress and uncompress the data of a file?
OutputStream:
Java application uses an output stream to write data to a destination, it may be a file,an array,peripheral device or socket.
InputStream:
Java application uses an input stream to read data from a source, it may be a file,an array,peripheral device or socket.
OutputStream class:
OutputStream class ia an abstract class.It is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink.
current output stream. 2) public void wrire(byte[])throws IOException: is used to write an array of byte to the current output stream. 3) public void flush()throws IOException: flushes the current output stream. 4) public void close()throws IOException: is used to close the current output stream.
InputStream class:
InputStream class ia an abstract class.It is the superclass of all classes representing an input stream of bytes.
FileOutputStream class:
A FileOutputStream is an output stream for writing data to a file. If you have to write primitive values then use FileOutputStream.Instead, for character-oriented data, prefer FileWriter.But you can write byte-oriented as well as character-oriented data.
import java.io.*; class Test{ public static void main(String args[]){ try{ FileOutputstream fout=new FileOutputStream("abc.txt"); String s="Sachin Tendulkar is my favourite player"; byte b[]=s.getBytes(); fout.write(b);
FileInputStream class:
A FileInputStream obtains input bytes from a file.It is used for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. It should be used to read byte-oriented data.For example, to read image etc.
Example of Reading the data of current java file and writing it into another file
We can read the data of any file using the FileInputStream class whether it is java file, image file, video file etc. In this example, we are reading the data of C.java file and writing it into another file M.java. import java.io.*; class C{ public static void main(String args[])throws Exception{ FileInputStream fin=new FileInputStream("C.java"); FileOutputStream fout=new FileOutputStream("M.java"); int i=0; while((i=fin.read())!=-1){ fout.write((byte)i); } fin.close(); } }
ByteArrayOutputStream class:
In this stream, the data is written into a byte array. The buffer automatically grows as data is written to it. Closing a ByteArrayOutputStream has no effect.
Output:success...
SequenceInputStream class:
SequenceInputStream class is used to read data from multipule streams.
Example of SequenceInputStream class that reads the data from two files and write it into another
In this example, we are writing the data of two files f1.txt and f2.txt into another file named f3.txt. //reading data of 2 files and writing it into one file import java.io.*; class Simple{ public static void main(String args[])throws Exception{ FileinputStream fin1=new FileinputStream("f1.txt"); FileinputStream fin2=new FileinputStream("f2.txt"); FileOutputStream fout=new FileOutputStream("f3.txt"); SequenceinputStream sis=new SequenceinputStream(fin1,fin2); int i; while((i.sisread())!=-1) { fout.write(i); } sis.close(); fout.close(); fin.close(); fin.close(); } }
Example of SequenceInputStream class that reads the data from multiple files using enumeration
If we need to read the data from more than two files, we need to have these information in the Enumeration object. Enumeration object can be get by calling elements method of the Vector class. Let's see the simple example where we are reading the data from the 4 files. import java.io.*; import java.util.*; class B{ public static void main(String args[])throws IOException{ //creating the FileInputStream objects for all the files FileInputStream fin=new FileInputStream("A.java"); FileInputStream fin2=new FileInputStream("abc2.txt"); FileInputStream fin3=new FileInputStream("abc.txt"); FileInputStream fin4=new FileInputStream("B.java"); //creating Vector object to all the stream Vector v=new Vector(); v.add(fin); v.add(fin2); v.add(fin3); v.add(fin4); //creating enumeration object by calling the elements method Enumeration e=v.elements(); //passing the enumeration object in the constructor SequenceInputStream bin=new SequenceInputStream(e); int i=0; while((i=bin.read())!=-1){ System.out.print((char)i); } bin.close(); fin.close(); fin2.close(); } }
BufferedOutputStream class:
BufferedOutputStream used an internal buffer. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast.
import java.io.*; class Test{ public static void main(String args[])throws Exception{ FileOutputStream fout=new FileOutputStream("f1.txt"); BufferedOutputStream bout=new BufferedOutputStream(fout); String s="Sachin is my favourite player"; byte b[]=s.getBytes(); bout.write(b); bout.flush(); bout.close(); System.out.println("success"); } } Output:success...
FileInputStream fin=new FileInputStream("f1.txt"); BufferedInputStream bin=new BufferedInputStream(fin); int i; while((i=bin.read())!=-1) System.out.println((char)i); fin.close(); }catch(Exception e){system.out.println(e);} } } Output:Sachin is my favourite player
FileWriter class:
FileWriter class is used to write character-oriented data to the file. Sun Microsystem has suggested not to use the FileInputStream and FileOutputStream classes if you have to read and write the textual information.
FileReader class:
FileReader class is used to read data from the file.
import java.io.*; class Simple{ public static void main(String args[])throws Exception{ FileReader fr=new FileReader("abc.txt"); int i; while((i=fr.read())!=-1) System.out.println((char)i); fr.close(); } } Output:my name is sachin
CharArrayWriter class:
The CharArrayWriter class can be used to write data to multiple files. This class implements the Appendable interface. Its buffer automatically grows when data is written in this stream. Calling the close() method on this object has no effect.
import java.io.*; class Simple{ public static void main(String args[])throws Exception{ CharArrayWriter out=new CharArrayWriter(); out.write("my name is"); FileWriter f1=new FileWriter("a.txt"); FileWriter f2=new FileWriter("b.txt"); FileWriter f3=new FileWriter("c.txt"); FileWriter f4=new FileWriter("d.txt");
InputStreamReader class:
InputStreamReader class can be used to read data from keyboard.It performs two tasks: connects to input stream of keyboard converts the byte-oriented stream into character-oriented stream
BufferedReader class:
BufferedReader class can be used to read data line by line by readLine() method.
public static void main(String args[])throws Exception{ InputStreamReader r=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(r); System.out.println("Enter ur name"); String name=br.readLine(); System.out.println("Welcome "+name); } } Output:Enter ur name Amit Welcome Amit
Another Example of reading data from keyboard by InputStreamReader and BufferdReader class until the user writes stop
In this example, we are reading and printing the data until the user prints stop.
import java.io.*; class G5{ public static void main(String args[])throws Exception{ InputStreamReader r=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(r);
String name=""; while(name.equals("stop")){ System.out.println("Enter data: "); name=br.readLine(); System.out.println("data is: "+name); } br.close(); r.close(); } } Output:Enter data: Amit data is: Amit Enter data: 10 data is: 10 Enter data: stop data is: stop
Syntax:
java.util.Scanner class:
There are various ways to read input from the keyboad, the java.util.Scanner class is one of them. The Scanner class breaks the input into tokens using a delimiter which is whitespace bydefault. It provides many methods to read and parse various primitive values.
import java.util.Scanner; class ScannerTest{ public static void main(String args[]){ Scanner sc=new Scanner(System.in); System.out.println("Enter your rollno"); int rollno=sc.nextInt(); System.out.println("Enter your name"); String name=sc.next(); System.out.println("Enter your fee"); double fee=sc.nextDouble(); System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee); } } Output:Enter your rollno 111 Enter your name Ratan Enter 450000 Rollno:111 name:Ratan fee:450000
java.io.PrintStream class:
The PrintStream class provides methods to write data to another stream. The PrintStream class automatically flushes the data so there is no need to call flush() method. Moreover, its methods don't throw IOException.
import java.io.*; class PrintStreamTest{ public static void main(String args[])throws Exception{ FileOutputStream fout=new FileOutputStream("mfile.txt"); PrintStream pout=new PrintStream(fout); pout.println(1900); pout.println("Hello Java"); pout.println("Welcome to Java"); pout.close(); fout.close(); } }
class PrintStreamTest{ public static void main(String args[]){ int a=10; System.out.printf("%d",a);//Note, out is the object of PrintStream class } }
Output:10
import java.io.*; class PipedWR{ public static void main(String args[])throws Exception{ final PipedOutputStream pout=new PipedOutputStream(); final PipedInputStream pin=new PipedInputStream(); pout.connect(pin);//connecting the streams //creating one thread t1 which writes the data Thread t1=new Thread(){ public void run(){ for(int i=65;i<=90;i++){ try{ pout.write(i); Thread.sleep(1000); }catch(Exception e){} } } }; //creating another thread t2 which reads the data Thread t2=new Thread(){ public void run(){ try{ for(int i=65;i<=90;i++) System.out.println(pin.read()); }catch(Exception e){}
Serialization
1. Serialization 2. Serializable Interface 3. ObjectOutputStream class 4. Example of Serialization 5. Deserialization 6. ObjectInputStream class 7. Example of Deserialization 8. Serialization with Inheritance 9. Externalizable interface 10. Serialization and static datamember 11. Serializing the array or collection objects 12. Serializing the object of a class that has non-serialzable object 13. Deserializing the class object that have parameterized constructor only Serialization is a machanism of writing the state of an object into a byte stream. It is mainly used in Hibernate, JPA, EJB etc. The reverse operation of the serialization is called deserialization. The String class and all the wrapper classes implements Serializable interface bydefault.
Advantage of Serialization
It is mainly used to travel object's state on the network.
int id; String name; public Student(int id, String name) { this.id = id; this.name = name; } }
ObjectOutputStream class:
An ObjectOutputStream is used to write primitive data types and Java objects to an OutputStream.Only objects that support the java.io.Serializable interface can be written to streams.
Example of Serialization
In this example, we are going to serialize the object of Student class. The writeObject() method of ObjectOutputStream class provides the functionality to serialize the object. We are saving the state of the object in the file named f.txt.
import java.io.*; class Persist{ public static void main(String args[])throws Exception{ Student s1 =new Student(211,"ravi"); FileOutputStream fout=new FileOutputStream("f.txt"); ObjectOutputStream out=new ObjectOutputStream(fout); out.writeObject(s1); out.flush(); System.out.println("success"); } } Output:succss
Deserilization:
Deserialization is the process of reconstructing the object from the serialized state.It is the reverse operation of serialization.
ObjectInputStream class:
Example of Deserialization:
import java.io.*; class Depersist{ public static void main(String args[])throws Exception{ ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt")); Student s=(Student)in.readObject(); System.out.println(s.id+" "+s.name); in.close(); } } Output:211 ravi
int id; String name; public Student(int id, String name) { this.id = id; this.name = name; } }
class Student extends Person{ String course; int fee; public Student(int id, String name, String course, int fee) { super(id,name); this.course=course; tihs.fee=fee; } } Now you can serialize the Student class object that extends the Person class which is Serializable.Parent class properties are inherited to subclasses so if parent class is Serializable, subclass would also be.
Externalizable interface:
The Externalizable interface provides the facility of writing the state of an object into a byte stream in compress format. It is not a marker interface. The Externalizable interface provides two methods: public void writeExternal(ObjectOutput out) throws IOException public void readExternal(ObjectInput in) throws IOException
static String companyName="IBM";//it won't be serialized public Student(int id, String name) { this.id = id; this.name = name; } }
Rule: In case of array or collection, all the objects of array or collection must be serializable,if any object is not serilizable then serilization will be failed.
import java.io.Serializable; public class Student implements Serializable{ int id; String name; transient int age;//Now it will not be serialized public Student(int id, String name,int age) { this.id = id; this.name = name; this.age=age; } }
import java.io.*; class Persist{ public static void main(String args[])throws Exception{ Student s1 =new Student(211,"ravi",22);
FileOutputStream f=new FileOutputStream("f.txt"); ObjectOutputStream out=new ObjectOutputStream(f); out.writeObject(s1); out.flush(); System.out.println("success"); } } Output:succss