Day 9 IO Streams

Views:
 
Category: Entertainment
     
 

Presentation Description

No description available.

Comments

Presentation Transcript

Java IO Streams:

Java IO Streams

Objectives:

Objectives At the end of this session, you will be able to Use the classes and interfaces in java.io package Perform Read and Write operations on files Persist an object in a file Use Random access files Copyright © 2016 Tech Mahindra. All Rights Reserved.

Agenda:

Agenda Introduction to Streams Types of Streams Classes and interfaces in java.io package File IO Serialization StreamTokenizer Copyright © 2016 Tech Mahindra. All Rights Reserved.

I/O Application:

Typically, there are three ways a developer may use input and output: Files and directories Console: (standard-in, standard-out) Socket-based sources I/O Application Copyright © 2016 Tech Mahindra. All Rights Reserved.

Introduction to Streams:

Introduction to Streams A stream is an abstraction that helps a java program to work with external data local file user input network. File.txt Java Program { ….. ….. ….. ….. } InputStream OutputStream Copyright © 2016 Tech Mahindra. All Rights Reserved.

I/O Streams:

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 (sink), one item at time. I/O Streams Copyright © 2016 Tech Mahindra. All Rights Reserved.

Types of Streams:

Types of Stream s Byte Stream Byte streams provide an abstraction to read/write bytes, e.g. binary data InputStream and OutputStream are the abstract classes which represent Byte Streams Character Stream Usually works for Characters & Strings Follows the Unicode to support internationalization Reader and Writer are the abstract classes which represents Character Streams Stream Byte Streams Character Streams Source streams InputStream Reader Sink streams OutputStream Writer Copyright © 2016 Tech Mahindra. All Rights Reserved.

IO Class Hierarchy:

IO Class Hierarchy Object InputStream OutputStream Writer Reader Byte-Oriented Streams Character-Oriented Streams Copyright © 2016 Tech Mahindra. All Rights Reserved.

Types of Streams:

Types of Streams FileInputStream, DataInputStream Byte Oriented Streams Unicode Character Oriented Streams InputStream OutputStream Reader Writer FileOutputStream , DataOutputStream InputStreamReader OutputStreamWriter FileReader FileWriter I/O Streams May be buffered or unbuffered Abstract Classes Copyright © 2016 Tech Mahindra. All Rights Reserved.

Predefined Stream Objects:

Predefined Stream Objects The three predefined stream objects in Java are byte streams: System.out & System.err : System.out refers to standard output stream and System.err refers to standard error stream The default device for both these streams is console System.in System.in is the standard input stream. The default device is keyboard. Copyright © 2016 Tech Mahindra. All Rights Reserved.

Reading Console Input:

Reading Console Input Character-oriented stream can be used to read console input To get a character based stream System.in is wrapped in a BufferedReader . The keyboard sends data to the InputStream (System.in)which is connected to InputStreamReader stream which is further connected to a BufferedReader stream. BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in )); Java Program Copyright © 2016 Tech Mahindra. All Rights Reserved.

PrintWriter Class:

PrintWriter Class PrintWriter Class is used for output because: All writer classes provide for Unicode output , as opposed to ASCII output. You can print (or println ) any data type PrintWriter extends Writer and wraps either an OutputStream or a Writer . PrintWriter OutputStream Writer wraps wraps Copyright © 2016 Tech Mahindra. All Rights Reserved.

File class:

File class Objects of type File are used to represent the actual files or directories on the disk File class is not actually used to read/write data It is used for operations like making a new empty file, searching for files, deleting files, making directories etc Few noteworthy methods in File class boolean exists() – Returns true if it can find the actual file boolean createNewFile () – Creates a new file if it doesn’t exist boolean mkdir () – Creates an empty directory boolean delete() – Deletes a file Copyright © 2016 Tech Mahindra. All Rights Reserved.

File Streams:

File Streams File streams are primitive streams whose sources or destinations are files . The base file stream classes in java.io package are: FileInputStream   - binary file input base class FileOutputStream - binary file output base class FileReader              - read text files FileWriter               - write to text files All classes provide the read() and write() methods for I/O operations Copyright © 2016 Tech Mahindra. All Rights Reserved.

File IO Streams:

File IO Streams An input stream from a file can be created with : File file_in = new File ("data.dat"); FileInputStream in = new FileInputStream ( file_in ); Output streams to files are opened like: File file_out = new File("tmp.dat"); FileOutputStream out = new FileOutputStream ( file_out ); To append to an existing file use the overloaded constructor : File file_out = new File ("old.dat"); FileOutputStream out =new FileOutputStream ( file_out , true ); Copyright © 2016 Tech Mahindra. All Rights Reserved.

Buffered IO Streams:

Buffered IO Streams We can wrap a BufferedInputStream or BufferedOutputStream a round the FileInputStream or FileOutputStream for reading & storing large chunks of data in a buffer at once for later use FileInputStream fin = new FileInputStream (“data.dat”); BufferedInputStream bout = new BufferedInputStream (fin); The BufferedInputStream reads data from the File in large chunks and stores the data in an internal buffer We can then read data from the BufferedInputStream . Data is read from the buffer instead of directly from the file on each read File FileInputStream Java Program { ….. ….. ….. ….. } BufferedInputStream Internal Buffer Copyright © 2016 Tech Mahindra. All Rights Reserved.

Filter IO Streams:

Filter IO Streams FilterInputStream & FilterOutputStream provide no additional functionality, but serve as a base class for InputStream and OutputStream wrappers. Two commonly used subclasses of FilterInputStream are DataInputStream and BufferedInputStream and of FilterOutputStream are BufferedOutputStream and DataOutputStream DataInputStream BufferedInputStream FilterInputStream InputStream DataOutputStream BufferedOutputStream FilterOutputStream OutputStream wraps wraps Copyright © 2016 Tech Mahindra. All Rights Reserved.

Data Streams:

Data Streams The DataInputStream and DataOutputStream allow to read and write primitive data types to input and output streams respectively, rather than just bytes or characters Data streams are buffered. They process more than single byte at a time. It supports operations like readInt , writeInt , readFloat , writeFloat etc , DataOutputStream DataInputStream Copyright © 2016 Tech Mahindra. All Rights Reserved.

DataOutputStream:

DataOutputStream DataOutputStream extends FilterOutputStream ,which extends OutputStream It implements DataOutput interface . This interface defines methods that convert value of primitive type into a byte and then writes to underlying stream. DataOutputStream must be attached to some other OutputStream . Example : DataOutputStream is attached to a FileOutputStream to write to a file on the file system named File1.txt DataOutputStream dos = new DataOutputStream (new FileOutputStream (“File1.txt")); Copyright © 2016 Tech Mahindra. All Rights Reserved.

DataInputStream:

DataInputStream DataInputStream is complement of DataOutputStream It extends FilterInputStream , which extends InputStream . It implements DataInput interface . This interface reads a sequence of bytes and convert them into values of primitive type . Example: DataInputStream is attached to a FileInputStream to read a file on the file system named File1.txt DataInputStream dis = new DataInputStream (n ew FileInputStream (“File1.txt")); Copyright © 2016 Tech Mahindra. All Rights Reserved.

Stream Tokenizers:

Stream Tokenizers StreamTokenizer reads text streams as sequences of tokens. try { StringReader sr = new StringReader ("Hi! this is 1 Java Virtual 3 Guru from TechM "); StreamTokenizer st = new StreamTokenizer ( sr ); st.resetSyntax (); st.wordChars ('A', 'Z'); st.wordChars ('a', 'z'); int type; while ((type = st.nextToken ()) != StreamTokenizer.TT_EOF ) { if (type == StreamTokenizer.TT_WORD ) System.out.println ( st.sval ); } } catch ( IOException e) { System.err.println ("Error :" + e); } Copyright © 2016 Tech Mahindra. All Rights Reserved.

Serialization :

Serialization Serialization involves saving the current state of an object to a stream, and restoring an equivalent object from a stream. Objects are serialized by using ObjectOutputstream . They are deserialized by using ObjectInputStream . Static variables and transient variables are not serialized. Serialization also includes subclasses of a serialized class. Serialization is implemented using S erializable interface which is a marker interface without any methods Copyright © 2016 Tech Mahindra. All Rights Reserved.

Object I/O :

Object I/O The stream constructors are: ObjectInputStream ( InputStream inStreamObj ) ObjectOutputStream ( OutputStream outStreamObj ) The methods are: readObject () : returns the instance on an Object class. writeObject ( obj ) : grabs the data from the class fields of an existing object and sends that data through the stream. ObjectOutputStream oos = new ObjectOutputStream ( new FileOutputStream (“abc.txt”)); oos.writeObject (); ObjectInputStream ois = new ObjectInputStream ( new FileInputStream (“abc.txt”)); ois.readObject (); Copyright © 2016 Tech Mahindra. All Rights Reserved.

Externalizable:

Externalizable Sometimes customization requires before storing & after retrieving objects e.g. Encrypting passwords before storing In such case, implement java.io.Externalizable interface. Externalizable is a subinterface of Serializable . This interface declares two methods: readExternal () writeExternal () These two methods are called automatically after object’s serialization & deserialization Copyright © 2016 Tech Mahindra. All Rights Reserved.

Random Access Files :

Random Access Files The RandomAccessFile allows you to both read and write a file and also move to any point within the file. A random access file behaves like a large array of bytes stored in the file system. The RandomAccessFile object provides a file pointer that acts as a index to indicate where in the file a read or write operation begins File my_file = new File(“test.dat”); RandomAccessFile file_ro = new RandomAccessFile ( my_file , " rw "); O r RandomAccessFile file_ro = new RandomAccessFile (“test. dat ”," rw "); Copyright © 2016 Tech Mahindra. All Rights Reserved.

Try it out:

Try it out Q1. The ______ class allows us to manage (add, rename and delete) files and directories Q2. The FileReader and FileWriter are low level I/O classes that are to be wrapped around BufferedReader and BufferedWriter to get access to higher-level methods. ( True.False ) Q3. An attribute marked with _________ will not be written into file when the object is serialized Q4. IOException is a Runtime exception (True/False) Copyright © 2016 Tech Mahindra. All Rights Reserved.

Summary:

Summary In this session, we have covered: Introduction to Streams Types of Streams Classes and interfaces in java.io package File IO Serialization StreamTokenizer Copyright © 2016 Tech Mahindra. All Rights Reserved.

Thank you:

Thank you Copyright © 2016 Tech Mahindra. All Rights Reserved.