Java Basics Introduction to Streams
Topics To Be Covered Objectives Introduction to Streams Object Serialization Summary Quiz
Objectives Write programs using Byte Streams Serialize Objects At the end of this course, you will be able to: Write programs using Byte Streams Serialize Objects Write programs using Character Streams
Streams
Streams Files are used for Store Java classes, programs Store pictures, music, videos Can also use files to store program I/O A stream is a flow of input or output data Characters Numbers Bytes www.prolearninghub.com
Streams Key board input is a temporary data . When we close the program the data is vanished . But we can save that data in files for future use . It may be used for this program next time. It may be use in another program. Input stream Output stream Keyboard Monitor Input stream Output stream Hard disc Compact disc www.prolearninghub.com
Streams There are two types of files used in file programming : Binary files All data stored in the form of zero’s and one’s Movies, music and same files are binary files Text files It can be viewed by text editor and may also be edited . www.prolearninghub.com
Streams A text file and binary file having same values. 1 2 3 4 5 - 7 7 8 A binary file 12345 -4027 8 www.prolearninghub.com
Streams Output stream Output stream is used to write data in a file or array . Input stream Input stream is used to read data from the source. www.prolearninghub.com
Streams How do we take an input from keyboard? Input Streams are used to read data from any data source like keyboard, socket, file etc. Output Streams are used to write data to any data destination like console, socket, file etc. www.prolearninghub.com
Streams What is an I/O Stream? An abstract representation of data connected to some input or output device is called as Stream Java Program { … } InputStream File.txt OutputStream www.prolearninghub.com
Streams Two Types of Stream Classes: Byte Stream Character Stream Usually works for bytes & binary objects InputStreais and OutputStream are the abstract classes which represent Byte Streams Character Stream Usually works for Characters & Strings Follows the Unicode Introduced to cater to the needs of internationalization Reader and writer are the abstract classes which represents Character Streams www.prolearninghub.com
Streams May be buffered or unbuffered I/O Streams Byte Oriented Streams InputStream FileInputStream, DataInputStream OutputStream FileOutputStream, DataOutputStream Unicode Character Oriented Streams Reader InputStreamReader FileReader OutputStreamWriter FileWriter Writer Streams Abstract Classes May be buffered or unbuffered www.prolearninghub.com
Streams Byte Streams FileOutputStream & FilelnputStream classes: These are sub classes of OutPutStream and InPutStream Classes respectively These are used to write & read binary data and /or binary object to and from the data source FileOutputStream fos = new FileOutputStream (“abc.txt”); FilelnputStream fis = new FileInputStream (“abc.txt”); www.prolearninghub.com
read() returns -1 on encountering end of file Streams Byte Streams import java.io.*; public class ReadWriteFile { public static void main(String args[]) { try { FilelnputStream fis = new FilelnputStream(“Source.txt"); FileOutputStream fos = new FileOutputStream(“Dest.txt"); int nextByte ; while((nextByte = fis.read()) != -1) { fos.write((char)nextByte); System.out.println(nextByte); } fis.close(); fos.close(); catch (IOException e) { System.out.println("Error reading file" + e ); FilelnputStream object is used to read data from the file FileOutputStream object is used to write data to a file read() returns -1 on encountering end of file www.prolearninghub.com
Streams BufferedlnputStream & Buf feredOuputStream classes: Subclasses of InputStream & OutputStream classes respectively We can wrap a BufferedlnputStream around the FilelnputStream for reading and storing large chunks of data in a buffer at once for later use Java Program { … } BufferedInputStream File FileInputStream Internal Buffer We can then read data from the BufferedlnputStream. Data is read from the buffer instead of directly from the file on each read The BufferedlnputStream reads data from the File in large chunks and stores the data in an internal buffer www.prolearninghub.com
Streams BufferedlnputStream adds buffering to FilelnputStream object import java.io.*; public class BufferedDemo { public static void main(String[] args) { try { Bufferedlnputstream bufferedFile = new Bufferedlnputstream( new Filelnputstream(“Source.txt")); int nextByte; while ((nextByte = bufferedFile.read()) != -1) { System.out.print((char)nextByte); } } catch (IOException e) { System.out.println("Error reading file" + e); www.prolearninghub.com
Streams Data I/O Streams We may want an even higher level of abstraction and wish to read and write data to and from streams in the form of primitive data variables (rather than just bytes or characters) Java has built in stream classes to automatically handle converting this information into the necessary raw bytes that a stream can use www.prolearninghub.com
Streams DatalnputStream & DataOutputStream classes: import java.io.*; public class DataStream { public static void main(String[] args) { try { BufferedOutputStream bos = new BufferedOutputStream (new FileOutputStream("Number.txt”)); DataOutputStream dos = new DataOutputStream(bos); dos.writelnt(5); dos.close(); bos.close(); BufferedlnputStream bis = new BufferedlnputStream (new FileInputStream("Number.txt")); DatalnputStream dis = new DatalnputStream(bis); int n = dis.readInt(); System.out.println("Number in File is...” + n); dis.close(); bis.close(); } catch(IOException e) { System.out.println("Error writing to file” + e ); DatalnputStream & DataOutputStream classes: Allow to read and write primitive data types to input and output streams respectively www.prolearninghub.com
Streams Character Streams Two types of Character Stream classes: Reader Writer FileReader and Filewriter classes: Subclasses of Reader & writer class Used to read and write characters or strings from a data source like file Filewriter fw = new Filewriter("abc.txt",true); FileReader fr = new FileReader(“abc.txt"); www.prolearninghub.com
Streams BufferedReader & BufferedWriter classes: Provides buffering to Character streams Subclasses of Reader & writer classes BufferedReader is used to read data from console & files InputStreamReader class: Serves as a wrapper for any InputStream object Converts the raw bytes as they are read from the InputStream and serves them to the user as Unicode characters www.prolearninghub.com
Streams Reading data from console: We can wrap InputStreamReaders around InputStreams to make them useful In reading character data BufferedReader provides a readLine() method for additional functionality BufferedReader stdin = new BufferedReader (new InputStreamReader(Systeni.in)); try { String input = stdin.readline(); System.out.println("The input from the command line was " + input); } catch(IOException e) { System.err.println("Error reading data"); } www.prolearninghub.com
Common method used in output stream class Description 1) public void write(int)throws IOException: is used to write a byte to the current output stream. 2) public void write(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. www.prolearninghub.com
Common method used in input stream class Description 1) public abstract int read()throws IOException: reads the next byte of data from the input stream.It returns -1 at the end of file. 2) public int available()throws IOException: returns an estimate of the number of bytes that can be read from the current input stream. 3) public void close()throws IOException: is used to close the current input stream. www.prolearninghub.com
Example of Java FileOutputStream class import java.io.*; class Test{ public static void main(String args[]){ try{ FileOutputstream fout=new FileOutputStream("abc.txt"); String s=“This is file output stream"; byte b[]=s.getBytes(); //converting string into byte array fout.write(b); fout.close(); System.out.println("success..."); }catch(Exception e){system.out.println(e);} } } www.prolearninghub.com
Example of Java FileInputStream class import java.io.*; class SimpleRead{ public static void main(String args[]){ try{ FileInputStream fin=new FileInputStream("abc.txt"); int i=0; while((i=fin.read())!=-1){ System.out.println((char)i); } fin.close(); }catch(Exception e){system.out.println(e);} } } www.prolearninghub.com
Object Serialization
Object Serialization The process of writing the state of an object to a byte stream Saves the state of an Object to any data destination like file This may later be restored by the process of Deserialization Only an object that implements the Serilizable interface can be saved and restored by the serilization facilities The Serializable interface defines no members: It is simply used to indicate that a class may be serialized All subclasses of a serializable class are also serializable www.prolearninghub.com
Object Serialization ObjectOutputStream & ObjectlnputStream classe Subclasses of InputStream & OutputStream classes Same functionality as DatalnputStream & DataOutputStream Also includes support for reading and writing objects data via the readObject() & writeObject() methods Employee e1 = new Employee(12345, "Bipin Kabra"); ObjectOutputStream oos = new 0bject0utputstream( new FileOutputStream("Emp.txt”)); oos.writeobject(el); Employee e2 ; ObjectlnputStream ois = new ObjectlnputStream( new FilelnputStream("Emp.txt")); e2 = (Employee) ois.readObject(); www.prolearninghub.com
Object Serialization Serialization Example public class Employee implements Serializable{ private int empNo; private String eName; public Employee(int empNo, String eName) { this.empNo = empNo; this.eName = eName; } public int getEmpNo() { return empNo; public String getEName() { return eName; www.prolearninghub.com
Object Serialization Serialization Example www.prolearninghub.com import java.io.* ; public class SerializationDemo { public static void main(String[] args) { try{ Employee el = new Employee(1234, "Bhushan”); ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream("Emp.txt“)); oos.writeObject(el); Employee e2 ; ObjectlnputStream ois = new ObjectInputStream( new FileInputStream("Emp.txt“)); e2 = (Employee) ois.readObject(); System.out.println(e2.getEmpNo()+ “ ”+ e2.getEName()); } catch(Exception e){ System.out.printIn(e); www.prolearninghub.com
Summary In this session, we have covered: What is an I/O Stream? Types of Streams Byte Streams Object Serialization Character Streams www.prolearninghub.com
Assessment – Java Basics: Part 4 The quiz contains 10 questions. You will have one attempt to answer each question. You can exit the quiz at any time. If you exit the quiz without completing all 10 questions, on return you will have to start the quiz from the beginning. Scoring 80% or higher means you have understood the topic well. Start www.prolearninghub.com
For writing state of an object, which method is used? readObject() storeObject() writeObject() www.prolearninghub.com
Which class you will use for reading and storing large chunks of data in a buffer? BufferedInputStream FileInputStream FileOutputStream www.prolearninghub.com
Which of the following class allows to red primitive data? FileOutputStream DataInputStream FileInputStream www.prolearninghub.com
For reading the state of an object, which method is used? readObject() storeObject() writeObject() www.prolearninghub.com
Serialization is process of writing state of an object to a destination? True False www.prolearninghub.com
Which stream is used to write data to any destination? Input Output InputOutput www.prolearninghub.com
All subclasses of a serializable class are not serializable? True False www.prolearninghub.com
Which of the following is not an abstract class in stream family? DataInputStream InputStream OutputStream www.prolearninghub.com
The class whose state you want to write to a destination must interface? Serializable Externizable Storable www.prolearninghub.com
Find the odd one from following. Byte Steam Character Steam Bit Steam www.prolearninghub.com
The Results