Presentation is loading. Please wait.

Presentation is loading. Please wait.

Topic: File Input / Output

Similar presentations


Presentation on theme: "Topic: File Input / Output"— Presentation transcript:

1 Topic: File Input / Output
Course : JAVA PROGRAMMING Paper Code: ETCS-307 Faculty : Dr. Prabhjot Kaur Associate Professor, Dept. of Information Technology 1

2 File Basics Data can be stored or read from Files. Data stored in Files is often called persistent data. File is a collection of related records placed in a particular area on the disk. File is a class that directly deals with file system. File doesn’t specify how information is retrieved from or stored in files, it describes the properties of file. Its object is used to obtain or manipulate the information associated with the file such as permissions, date, time, directory path etc.

3 File class File myDir = new File(“C:\\CS311”);
File myFile = new File(“C:\\CS311\\junk.java”); File myFile = new File(“C:\\CS311”, “junk.java”); File myFile = new File(myDir, “junk.java”). Directory: is a file that contains the list of other files and directories. We can call list() to extract the list of other files and directories. String[] list()

4 File methods exists() isDirectory() isFile() canRead() canWrite()
isHidden() getName() createNewFile() getPath() getAbsolutePath() getParent() list() length() renameTo( newPath ) delete() mkdir()

5 Example: File methods Import java.io.*; class Dir { PSVM(-)
{ String dir=“/java”; File f1=new File(dir); if(f1.isDirectory()) { S.O.P(“Directory of” + dir); String s[]=f1.list(); for (int i=0; i<s.length; i++) { File f=new File(dir+”/”+s[i]); if (f.isDirectory()) S.O.P(s[i]+ “is a directory”); else S.O.P(s[i]+ “is a File”); }} S.O.P(dir+ “is not a directory”); }

6 Streams Java file I/O involves streams. You write and read data to streams. The purpose of the stream abstraction is to keep program code independent from physical devices. Three stream objects are automatically created for every application: System.in, System.out, and System.err. A stream presents a uniform, easy-to-use, object oriented interface b/w program and I/O devices It is a path along which data flows.

7 Overview of I/O Streams
To bring in information, a program opens a stream on an information source (a file, keyboard, mouse, disk, memory, a socket) and reads the information sequentially, as shown in the following figure.

8 Overview of I/O STREAMS
Similarly, a program can send information to an external destination by opening a stream to a destination and writing the information out sequentially, as shown in the following figure.

9 Types of Streams The java.io package contains a collection of stream classes that support algorithms for reading and writing. To use these classes, a program needs to import the java.io package. There are 2 kinds of streams byte streams character streams Byte Oriented Each datum is a byte uses InputStream class hierarchy & OutputStream class hierarchy Character-based I/O streams each datum is a Unicode character uses Reader class hierarchy & Writer class hierarchy

10 Types of Streams Streams are unidirectional. They can send data only in one direction that’s why Java provides two kinds of Byte as well as Character streams.

11 Byte Oriented Streams There are many different types of Byte-Oriented Streams Represented by different classes within the java.io.package All byte-oriented streams are subclasses of a common Stream class Input Streams are subclasses of the abstract class java.io.InputStream Output Streams are subclasses of the abstract class java.io.OutputStream All byte-oriented streams inherit basic methods from their respective superclasses Some define new methods pertinent to the type of data they provide. Byte-oriented streams are closely related to the I/O streams provided by other programming languages like C, C++, and pascal. Because they are byte-oriented they are suitable for reading binary and ASCII data. Byte-oriented streams do not work well with unicode text. Use character oriented streams for unicode.

12 Byte Oriented Streams Byte streams create binary files. A binary file essentially contains the memory image of the data. That is, it stores bits as they are in memory. Binary files are faster to read and write because no translation need take place. Binary files, however, cannot be read with a text editor.

13 Byte-Oriented Input Stream Classes
The following is the byte-oriented input stream class hierarchy: InputStream ByteArrayInputStream FileInputStream FilterInputStream ObjectInputStream PipedInputStream SequenceInputStream BufferedInputStream DataInputStream PushbackInputStream ZipInputStream ZipInputStream is defined in: java.util.zip

14 InputStream Methods Reading There are 3 main read methods:
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 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 (max = size of 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]

15 InputStream Methods available() method returns the number of bytes which can be read without blocking skip() method skips over a number of bytes in the input stream close() method will close the input stream and release any system resources input streams optionally support repositioning the stream can mark the stream at a certain point and 'rewind' the stream to that point later. methods that support repositioning are: markSupported() returns true if repositioning is supported mark() places a mark in the stream reset() 'rewinds' the stream to a previously set mark

16 Creating an InputStream
InputStream is an abstract class Programmers can only instantiate subclasses. 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

17 Creating an InputStream
ObjectInputStream Created from another input stream (such as FileInputStream) Reads bytes from the stream (which represent serialized Objects) and converts them back into Objects More on Serialization later in the Chapter. PipedInputStream: Connects to an Instance of PipedOutputStream A pipe represents a one-way stream through which 2 threads may communicate Thread1 writes to a PipedOutputStream Thread2 reads from the PipedInputStream SequenceInputStream: Constructor takes multiple InputStreams Allows reading. When one stream ends, it continues reading from next stream in the list

18 Byte-Oriented Output Stream Classes
The following is the byte-oriented input stream class hierarchy: OutputStream ByteArrayOutputStream FileOutputStream FilterOutputStream ObjectOutputStream PipedOutputStream BufferedOutputStream DataOutputStream PrintStream ZipOutputStream ZipOutputStream is defined in: java.util.zip

19 OutputStream Methods Writing: There are 3 main write methods:
write() methods write 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 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]

20 OutputStream Methods flush() close()
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.

21 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.

22 Creating an OutputStream
ObjectOutputStream Created from another output stream (such as FileOutputStream) Programmers serialize objects to the stream using the writeObject() method More on Serialization later in the Chapter. PipedOutputStream: Connects to an Instance of PipedInputStream A pipe represents a one-way stream through which 2 threads may communicate Thread1 writes to a PipedOutputStream Thread2 reads from the PipedInputStream

23 Character-Oriented Streams
There are many different types of Character-Oriented Streams Represented by different classes within the java.io.package All character-oriented streams are subclasses of an abstract class Writers are subclasses of the abstract class java.io.Writer Readers are subclasses of the abstract class java.io.Reader All character-oriented streams inherit basic methods from their respective superclasses Some define new methods pertinent to the type of data they provide. Character oriented streams can be used in conjunction with byte-oriented streams: Use InputStreamReader to "convert" an InputStream to a Reader Use OutputStreamWriter to "convert" an OutputStream to a Writer

24 Character-Oriented Streams
Character streams create text files. These are files designed to be read with a text editor. Java automatically converts its internal unicode characters to the local machine representation (ASCII in our case).

25 Character-Oriented Reader Classes
The following is the byte-oriented input stream class hierarchy: Reader BufferedReader CharArrayReader FilterReader PipedReader StringReader InputStreamReader LineNumberReader PushbackReader FileReader

26 Reader Methods Reading There are 3 main read methods:
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 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 (max = size of 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]

27 Reader Methods close() method closes the stream
mark(int readAheadLimit) marks the current location Parameter specifies the 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 returns true if the stream is guaranteed not to block upon next read. reset() returns the stream to its previously marked location skip(long n) skips over n bytes

28 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. FilterReader An abstract class for filtering character streams Filtering will be discussed later in the chapter

29 Creating a Reader Object
InputStreamReader This class acts as a bridge from byte streams to character streams InputStreamReader takes an InputStream parameter to its constructor 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 A pipe represents a one-way stream through which 2 threads may communicate Thread1 writes to a PipedWriter Thread2 reads from the PipedReader StringReader Provides a character stream where the data is obtained from a String

30 Creating a Reader Object
LineNumberReader (subclass of BufferedReader) A stream which keeps track of how many lines there have been A line is terminated with a linefeed, carriage return or a carriage return followed immediately by a linefeed. PushbackReader (subclass of FilterReader) A stream which allows characters to be pushed back into the stream after being read The number of characters which can be pushed back is specified when instantiated. Default = 1 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.

31 Character-Oriented Writer Classes
The following is the byte-oriented input stream class hierarchy: Writer BufferedWriter CharArrayWriter OutputStreamWriter PipedWriter FileWriter PrintWriter StringWriter

32 Writer Methods There are 5 main write methods: void write(int c)
Writes a single character. void write(char[] buffer) Writes an array of characters void write(char[] buffer, int offset, int length) Writes a portion of an array of characters First character written is starts at buffer[offset] length indicates how many characters to write. void write(String aString) Writes aString to the stream void write(String aString, int offset, int length) Writes a portion of a String to the stream First character written is starts at aString.charAt(offset)

33 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 Filtering will be discussed later in the chapter

34 Creating a Writer Object
OutputStreamWriter This class acts as a bridge from character streams to byte streams OutputStreamWriter takes an OutputStream parameter to its constructor 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 A pipe represents a one-way stream through which 2 threads may communicate Thread1 writes to a PipedWriter Thread2 reads from the PipedReader StringWriter Characters written to this stream are collected in a StringBuffer. The StringBuffer can be used to construct a String.

35 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 When println is used, the stream will output the appropriate sequence (either linefeed, carriage return or carriage return/linefeed) for the current platform 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 Alternatively, open the file using a FileOutputStream and then pass that stream to an OutputStreamWriter instance.

36 Classes Java has 6 classes to support stream I/O
File: An object of this class is either a file or a directory. OutputStream: base class for byte output streams InputStream: base class for byte input streams

37 Classes Writer: base class for character output streams.
Reader: base class for character input streams. RandomAccessFile: provides support for random access to a file. We can read and write bytes, text to any location of file. StreamTokenizer: for breaking up a stream of text from an input text file into meaningful pieces called tokens.

38 Reading and Writing a Text File

39 Reading and Writing Text Files
To write to a text file, use a PrintWriter To read from a text file use InputStreamReader: to read one char at a time BufferedReader: read one line at a time StreamTokenizer: read one word at a time

40 FileWriter Class The FileWriter class is a convenience class for writing character files. One version of the constructor take a string for a file name, another version takes an object of the File class. Both versions of the constructor above have forms that take an additional boolean. If true, the data is appended to the file; if false, the file is overwritten.

41 PrintWriter PrintWriter is a useful class for making text files because it has methods print() and println() One version of the constructor takes an FileWriter object and a boolean. If the boolean it true, then the stream is flushed whenever a println() is called.

42 Example Disk = new PrintWriter(new( FileWriter(“my_file.txt” ),true);
Disk.println( “Hello World” ); Disk.close();

43 I/O Exceptions EOFException – end of file reached unexpectedly
FileNotFoundException – file could not be found InterruptedIOException – I/O operation has been interrupted. IOException – I/O exception of some kind has occur.

44 Example - Copy a File 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) System.out.println("Error:" + x);

45 Filter Streams What are filter streams? Example:
Filter streams are similar to filters in Unix The basic idea is that while the data is being read (or written) the data is modified by a filter or series of filters. How the data is modified is depends on which filters are used. Filters can be chained together. Example: A programmer creates a FileOuputStream OutputStreams are byte-oriented, but the programmer wishes to use character-oriented streams instead. The programmer knows that the OutputStreamWriter class can convert between character oriented streams and byte oriented streams The programmer creates an OuputStreamWriter and passes the FileOutputStream reference to it The programmer wishes to improve performance using a BufferedWriter. The programmer creates a BufferedWriter and passes the OutputStreamWriter object to the constructor

46 Filter Streams - Example
import java.io.*; public class MyClass { public void test() try FileOutputStream out = new FileOutputStream("Test"); OutpuStreamWriter oswOut = new OutputStreamWriter(out); BufferedWriter bufOut = new BufferedWriter(oswOut); // programmer now uses bufOut } catch (IOException x) bufOut oswOut out FileOutputStream OutputStreamWriter BufferedWriter Programmer Writes Data File named "Test" Data Buffered in Character Data converted to byte data Byte Data written to file

47 Dealing with primitive data types

48 Dealing with primitive data types
If we want to read/write the primitive data types, we can use filter classes as wrappers on existing I/P and O/P streams. The two filter classes are DataInputStream and DataOutputStream readByte() readBoolean() readChar() readShort() readInt() readLong() readFloat() readDouble() writeByte( int value ) writeBoolean( boolean value ) writeChar( int value ) writeShort( int value ) writeInt( int value ) writeLong( long value ) writeFloat( float value ) writeDouble( double value )

49 Example

50 Concatenating and buffering files
It is possible to combine 2 or more I/P files into single input stream using SequenceInputStream. Java also support creation of buffers to store temporarily data that is read from or written to stream. Buffers can be created using BufferedInputStream and BufferedOutputStream.

51 Concatenating and buffering files

52 Random Access Files A random access file allows you to read and write a file at any point. Methods that move the file pointer seek( long position ) getFilePointer(): returns long length(): returns long

53 Random Access Files Constructor for a random access file
the constructor takes two arguments. The first identifies the file The second is “rw” or “r” RandomAccessFile F = new RandomAccessFile( “myFile”, “rw” ) To use a random access file successfully, the data must be broken into fixed size units.

54 Random Access Files

55 PushbackInputStream One of the use of buffering is the implementation of pushback. Pushback is used on an input stream to allow a byte to be read and then returned to the stream. Constructors: PushbackInputStream(InputStream i) PushbackInputStream(InputStream i, int num) unread() method

56 PushbackInputStream import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.PushbackInputStream; public class JavaPushbackInputStreamExamples  { public static void main(String[] args) String strExpression = "a = a++ + b;"; //get bytes from the expression string   byte bytes[] = strExpression.getBytes(); ByteArrayInputStream bis = new ByteArrayInputStream(bytes); PushbackInputStream pis = new PushbackInputStream(bis);  int ch;   try   {   while( (ch = pis.read())!= -1)   {    if(ch == '+')   {     if( (ch = pis.read()) == '+')     {System.out.print("Plus Plus");  }     else     {  pis.unread(ch);         System.out.print("+");  }    } else     {  System.out.print((char)ch);   }     }    }catch(IOException ioe)                 { System.out.println("Exception while reading" + ioe);  } }

57 Object Serialization When an object is instantiated, the system reserves enough memory to hold all of the object's instance variables The space includes inherited instance variables. The object exists in memory. Instance methods read and update the memory for a given object. The memory which represents an object can be written to an ObjectOutputStream. Objects are serialized to an ObjectOutputStream

58 Object Serialization Any other objects referred to by the Serialized object are also serialized to the stream Unless they are marked as "transient" When an object is serialized, the stream checks to ensure that the object implements the java.io.Serializable interface. If not, the Stream throws a NotSerializableException The Serializable interface does not define any methods.

59 Object Streams To read and write objects, do the following
make the class serializable by adding implements Serializable to the class definition Use the ObjectInputStream and ObjectOutputStream classes along with the writeObject() and readObject() methods.

60 Example – writing an Object
import java.io.*; public class Test { public void saveObject(String outputFilename, Object anObject) try FileOutputStream fpout = new FileOutputStream(outputFilename); ObjectOutputStream obOut = new ObjectOutputStream(fpout); obOut.writeObject(anObject); obOut.flush(); obOut.close(); } catch (IOException x) System.out.println("Error:" + x);

61 Example - reading an Object
import java.io.*; public class Test { public Object readObject(String inputFilename) try FileInputStream fpin = new FileInputStream(inputFilename); ObjectInputStream obIn = new ObjectInputStream(fpin); Object anObject = obIn.readObject(); obIn.close(); return anObject; } catch (IOException x) System.out.println("Error:" + x);

62 Example - Serialize an Object and Compress
import java.io.*; import java.util.zip.*; public class Test { public void saveObject(String outputFilename, Object anObject) try FileOutputStream fpout = new FileOutputStream(outputFilename); DeflaterOutputStream dOut = new DeflaterOutputStream(fpout); ObjectOutputStream obOut = new ObjectOutputStream(dOut); obOut.writeObject(anObject); obOut.flush(); obOut.close(); } catch (IOException x) System.out.println("Error:" + x);

63 Example - Read in a Compressed Serialized Object
import java.io.*; public class Test { public Object readObject(String inputFilename) try FileInputStream fpin = new FileInputStream(inputFilename); InflaterInputStream inflateIn = new InflaterInputStream(fpin); ObjectInputStream obIn = new ObjectInputStream(inflateIn); Object anObject = obIn.readObject(); obIn.close(); return anObject; } catch (IOException x) System.out.println("Error:" + x);

64 THANKS FOR LISTENING PATIENTLY


Download ppt "Topic: File Input / Output"

Similar presentations


Ads by Google