Java Basics Introduction to Streams.

Slides:



Advertisements
Similar presentations
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. 2 Operating System Application #1 Application #2 Java Virtual Machine #1 Local Memory Shared Memory Threads.
Advertisements

I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
1 Streams and Input/Output Files Part I. 2 Introduction So far we have used variables and arrays for storing data inside the programs. This approach poses.
Jan Java I/O Yangjun Chen Dept. Business Computing University of Winnipeg.
Lecture 15: I/O and Parsing
Exceptions. Definition Exception: something unexpected that can occur in the execution of a program e.g., divide by zero or attempt to open a file that.
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
COMP201 Java Programming Topic 5: Input and Output Reading: Chapter 12.
Geoff Holmes Overview IO Zoo Stream I/O File I/O Buffering Random-Access Text Streams Examples Serialization Java IO – programs that start with import.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
Advanced Java Class Serialization. Serialization – what and why? What? –Translating the contents of an Object to a series of bytes that represent it,
Java I/O – what does it include? Command line user interface –Initial arguments to main program –System.in and System.out GUI Hardware –Disk drives ->
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Java I/O Input: information brought to program from an external source
CS203 Programming with Data Structures Input and Output California State University, Los Angeles.
CIS 068 JAVA I/O: Streams and Files. CIS 068 I/O Usual Purpose: storing data to ‘nonvolatile‘ devices, e.g. harddisk Classes provided by package java.io.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
Working with files By the end of this lecture you should be able to: explain the principles of input and output and identify a number of different input.
Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Text Input and Output on the Console.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Java How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
Based on OOP with Java, by David J. Barnes Input-Output1 The java.io Package 4 Text files Reader and Writer classes 4 Byte stream files InputStream, FileInputStream,
JAVA I/O © EnhanceEdu, IIIT Hyderabad. Contents 3/29/2010EnhanceEdu, IIIT - H 2  Command Line I/O  File Class  Streams  Byte Streams [Low level and.
12-CRS-0106 REVISED 8 FEB 2013 Java Collection. 12-CRS-0106 REVISED 8 FEB 2013 Java Collection.
The Java I/O Classes and Interfaces cont’d
Input/output Input in java is stream based.A stream represents sequence of bytes or characters. Stream provides an abstract view of I/O. Stream can be.
Two Ways to Store Data in a File  Text format  Binary format.
CIS 270—App Dev II Big Java Chapter 19 Files and Streams.
Introduction to Computation and Problem Solving Class 29: Introduction to Streams Prof. Steven R. Lerman and Dr. V. Judson Harward.
1 Software 1 Java I/O. 2 The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
Read and Write Files  By the end of this lab you will be able to:  Write a file in internal storage  Read a file from internal storage  Write a file.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
Exception Handling, Reading and Writing in Files, Serialization, Exceptions, Files, Streams, File Readers and Writers, Serializable SoftUni Team Technical.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 20.
Files and Serialization. Files Used to transfer data to and from secondary storage.
CSI 3125, Preliminaries, page 1 Files. CSI 3125, Preliminaries, page 2 Reading and Writing Files Java provides a number of classes and methods that allow.
Simple Java I/O Part I General Principles. Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
Java Input / Output l a modular approach to input/output: - different stream objects are connected/wrapped to handle I/O l a data stream object: a flow.
Java I/O 1. Java I/O (Input and Output) is used to process the input and produce the output based on the input. The java.io package contains all the classes.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
Java IO Exploring the java.io package and living to talk about it.
The Java IO System Different kinds of IO Different kinds of operations
CSC1351 Class 6 Classes & Inheritance.
Keerthi Nelaturu Url: site.uottawa.ca/~knela006
Lecture 8: I/O Streams types of I/O streams Chaining Streams
CSG2H3 Object Oriented Programming
Exception Handling, Reading and Writing in Files, Serialization,
Ch14 Files and Streams OBJECTIVES
Object Writing in files
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
File.
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
File I/O & collection frame work
Programming in Java Files and I/O Streams
Java Programming Course
JAVA IO.
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
Stream Oriented I/O Computer Programming II Dr. Tim Margush
Input and Output Stream
CSC 143 Java Streams.
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Files and Streams in Java
Web Design & Development Lecture 8
David Davenport Spring 2005
Presentation transcript:

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