Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6 Streams and Files IO

Similar presentations


Presentation on theme: "Chapter 6 Streams and Files IO"— Presentation transcript:

1 Chapter 6 Streams and Files IO
Marks -12

2 Chapter Goals To be able to read and write text files
To become familiar with the concepts of text and binary formats To understand when to use sequential and random file access

3 Introduction Variables and arrays are used for storing data inside the programs. This approach poses the problems- The data is lost when program is terminated. It is difficult to handle large volume of data using variables and arrays.

4 Introduction File : A file is collection of related records placed in a particular area on disk. Record : A record is composed of several fields. Fields : A field is group of characters Character : A Character in java is sequence of Unicode characters.

5 Data Representation in java Files
1 h n Byte Unicode Character John 1001 70.50 Lata 1002 57.50 Mani 1003 75.00 Viju 1004 82.50 Field 4 Characters Record 3 Fields File 4 Records

6 Introduction File Processing
Storing and managing data using files is known as file processing. It includes Creating files, Updating files and Manipulation of data.

7 Concept of Streams In file processing, input refers to the flow of data into a program and Output means the flow of data out of a program. Keyboard Mouse Memory Disk Network Printer Screen Java Program Input Output

8 Concept of Streams Streams represent the ordered sequence of data.
A stream in java is a path along which data flows (like river or pipe). It has source and destination. Stream

9 Streams Java Streams are classified in two basic types
Input Stream Output Stream An Input Stream extracts data from the source (file) and sends it to the program. An Output stream takes data from the program and sends (i.e. writes) it to the destination (file).

10 Input and Output Streams
Streams can be used to filter data. One stream used to get raw data in binary format and then use another stream in series to convert it to integers Source Program Reads Input Stream Destination Program Writes Ouput Stream

11 Stream Classes Byte Stream classes handle I/O operations on Bytes.
The java.io package contains number of stream classes for processing all type of data. These classes are categorized in two groups Byte Stream classes Character Stream Classes Byte Stream classes handle I/O operations on Bytes. Character Stream classes manage I/O operations on Characters.

12 Character Stream Classes
Java Stream Classes Java Stream Classes Character Stream Classes Writer Classes Reader Classes File Byte Stream Classe Output Stream Classes Input Stream Classes Memory Pipe

13 Byte Stream Classes Byte stream classes provide functional features for creating and manipulating streams and files for reading and writing bytes. The streams are unidirectional therefore java provides two types of byte streams classes: Input stream classes and output stream classes.

14 Input Stream Classes InputStream ByteArray FileInputStream
SequenceInputStream ObjectInputStream PipedInputStream FilterInputStream BufferedInputStream DataInputStream PushbackInputStream DataInput Hierarchy of Input Stream Classes

15 Input Stream Classes Reading Bytes Closing streams
The Super class InputStream is abstract class. It defines methods for performing functions such as – Reading Bytes Closing streams Marking position in streams Skipping Ahead in stream Finding the number of bytes in a stream

16 InputStream Methods read() -: Reads a byte from input stream. read( byte b[]) :- Reads an array of bytes into b. read( byte b[], int n, int m) :- Reads m bytes into b starting from nth byte available( ) :- Gives number of bytes availble in the input skip( n) :- Skips over n bytes from the input stream reset( ) :- Goes back to the beginning of the stream close( ) :- Closes the input stream

17 InputStream Methods The DataInputStream Class extends FilterInputStream and implements interface DataInput. So additional methods are available: readShort( ) readChar( ) readLine( ) readFloat( ) readInt( ) readBoolean( ) readUTF( ) readLong( ) readDouble( )

18 InputStream Methods Reading
read() methods will block until data is available to be read two of the three read() methods return the number of bytes read. -1 is returned if the Stream has ended. throws IOException if an I/O error occurs. This is a checked exception

19 Output Stream Classes There are 3 main read methods: int read()
Reads a single character. Returns it as integer int read(byte[] buffer) Reads bytes and places them into buffer returns the number of bytes read int read(byte[] buffer, int offset, int length) Reads up to length bytes and places them into buffer First byte read is stored in buffer[offset]

20 Creating an InputStream
ByteArrayInputStream: Constructor is provided with a byte array. This byte array contains all the bytes provided by this stream Useful if the programmer wishes to provide access to a byte array using the stream interface. FileInputStream: Constructor takes a filename, File object or FileDescriptor Object. Opens a stream to a file. FilterInputStream: Provides a basis for filtered input streams

21 Byte-Oriented Output Stream Classes
ByteArrayOutputStream FileOutputStream PipedOutputStream FilterOutputStream ObjectOutputStream DataOutputStream BufferedOutputStream PrintStream DataOutput

22 OutputStream Methods Writing:
write() method writes data to the stream. Written data is buffered. Use flush() to flush any buffered data from the stream. throws IOException if an I/O error occurs. This is a checked exception

23 There are 3 main write methods:
void write(int data) Writes a single character Note: even though data is an integer, data must be set such that: 0 <= data <= 255 void write(byte[] buffer) Writes all the bytes contained in buffer to the stream void write(byte[] buffer, int offset, int length) Writes length bytes to stream starting from buffer[offset]

24 OutputStream Methods flush()
To improve performance, almost all output protocols buffer output. Data written to a stream is not actually sent until buffering thresholds are met. Invoking flush() causes the OutputStream to clear its internal buffers. close() Closes stream and releases any system resources.

25 Creating an OutputStream
OutputStream is an abstract class. Programmers instantiate one of its subclasses ByteArrayOutputStream: Any bytes written to this stream will be stored in a byte array The resulting byte array can be retrieved using toByteArray() method. FileOutputStream: Constructor takes a filename, File object, or FileDescriptor object. Any bytes written to this stream will be written to the underlying file. Has one constructor which allows for appending to file: FileOutputStream(String filename, boolean append) FilterOutputStream: Provides a basis for Output Filter Streams. Will be covered later in chapter.

26 public class CopyFile {
import java.io.*; public class CopyFile { public void copyFile( String inputFilename, String outputFilename) { try { FileInputStream fpin = new FileInputStream(inputFilename); FileOutputStream fpout = new FileOutputStream(outputfilename); byte buffer = new byte[8192]; int length = 0; while ((length = fpin.read(buffer, 0, buffer.length)) > 0) { fpout.write(buffer, 0, length); } fpout.flush(); fpout.close(); fpin.close(); } catch (IOException x) {}}}

27 Character Stream Classes
Reader PipedReader CharArrayReader StringReader InputStreamReader BufferedReader FilterReader FileReader LineNumberReader PushbackReader

28 Reader class Methods Reading
read() methods will block until data is available to be read two of the three read() methods return the number of bytes read -1 is returned if the Stream has ended throws IOException if an I/O error occurs. This is a checked exception

29 Reader class Methods There are 3 main read methods: int read()
Reads a single character. Returns it as integer int read(char[] buffer) Reads bytes and places them into buffer returns the number of bytes read int read(char[] buffer, int offset, int length) Reads up to length bytes and places them into buffer First byte read is stored in buffer[offset]

30 Reader class Methods close() method closes the stream
mark(int readAheadLimit) - marks the current location Parameter specifies number of characters which can be read before the marks becomes invalid ready() returns true if there is data to be read from the stream reset() returns the stream to its previously marked location skip(long n) skips over n bytes

31 Creating a Reader Object
Reader is abstract. Programmers instantiate one of its subclasses. BufferedReader Reads text from the character input stream Provides buffering to provide efficient reading of characters, arrays and lines CharArrayReader Similar to ByteArrayInputStream Constructor takes a character array. The character array provides the characters for the stream.

32 Creating a Reader Object
InputStreamReader This class acts as a bridge from byte streams to character streams The InputStreamReader reads bytes from the InputStream and translates them into characters according to the specified encoding. PipedReader Similar to PipedInputStream Connects to an Instance of PipedWriter

33 Creating a Reader Object
StringReader Provides a character stream where the data is obtained from a String. FileReader (subclass of InputStreamReader) A convenience class to provide a character based stream from file. Alternatively, open the file using a FileInputStream and then pass that stream to an InputStreamReader instance.

34 Character-Oriented Writer Classes
PipedWriter CharArrayWriter FileWriter StringWriter BufferedWriter OutputStreamWriter PrintWriter FileWriter

35 Writer Methods There are 5 main write methods:
void write(int c) :Writes a single character. void write(char[] buffer) :Writes an array of chars. void write(char[] buffer, int offset, int length) : Writes a portion of an array of characters starting at offset length indicates characters to write. void write(String aString) :Writes aString to stream. void write(String aString, int offset, int length) Writes a portion of a String to the stream starts at offset , length indicates characters to write.

36 Creating a Writer Object
Writer is abstract. Programmers instantiate one of its subclasses. BufferedWriter :Writes text to the character stream Provides buffering to provide efficient writing of characters, arrays and lines CharArrayWriter :Similar to ByteArrayOutputStream Characters written to the stream are stored in a buffer. The buffer can be retrieved by calling toCharArray() or toString() FilterWriter An abstract class for writing filtered character streams

37 Creating a Writer Object
OutputStreamWriter This class acts as a bridge from character streams to byte streams Characters written to the OutputStreamWriter are translated to bytes (based on the encoding) and written to the underlying OuputStream. PipedWriter Similar to PipedOutputStream Connects to an Instance of PipedReader StringWriter Characters written to this stream are collected in a StringBuffer. The StringBuffer can be used to construct a String.

38 Creating a Writer Object
PrintWriter Provides print() and println() methods for standard output both print() and println() are overloaded to take a variety of types System.out and System.err are PrintWriters FileWriter (subclass of OutputStreamWriter) A convenience class for writing characters to file FileWriters assume that the default character encoding is acceptable

39 Input Stream Vs Reader Class
Input Stream Class Reader Stream Class Input Streams are used to read bytes from stream. Reader class reads character streams Useful for binary data such as images,video,and serialized objects. Reader class is used to read character data. Input stream is byte oriented A reader is Character Oriented.

40 Output Stream Vs Writer Class
Output Streams are used to write bytes to stream. Writer classes are used to write character streams. An output stream is byte oriented An writer is character oriented. OutputStream classes are used to write 8 bit bytes. Writer class is used to write 16 bit Unicode character stream

41 File Streams A file class is defined in package java.io. A file can be created using File class. Example : File f; f= new File(String Filename); The File class contains methods to perform various file operations. Creating a file, Opening a file, Closing a file, Deleting a file, Getting name of file , etc.

42 File Class Methods String getName(): Returns the name of file. String getParent(): Returns name of parent directory. boolean exists(): Returns true if file exists. String getPath():Gets the path of file. String list(): List the files in directory boolean createNewFile(): creates new File. boolean delete(): deletes the file or directory

43 FileInputStream and FileOutputStream
The File class explains only the file System. Java provides two special stream classes to read and write into file. These two classes operate onto files in native file system. These two classes are subclass of InputStream and outputstream classes respectively.

44 Serialization Serialization means storing an object in storage medium (file/ memory buffer) or to transmit it over a network in binary form.


Download ppt "Chapter 6 Streams and Files IO"

Similar presentations


Ads by Google