Unit 8 IO Programming Prof Arjun V Bala
Unit – 8 IO Programming Prof. Arjun V. Bala � 9624822202 �arjun. bala@darshan. ac. in OO Programming with JAVA (2150704) Darshan Institute of Engineering & Technology
Stream § The java. io package contains all the classes required for input output operations. § All streams represent an input source and an output destination. § The stream in the java. io package supports all the datatype including primitive. § A stream can be defined as a sequence of data. § There are two kinds of Streams • Input. Stream : The Input. Stream is used to read data from a source. • Output. Stream : The Output. Stream is used for writing data to a destination. Unit – 8 : IO Programming 2 Darshan Institute of Engineering & Technology
Byte Streams § Java byte streams are used to perform input and output of 8 -bit bytes. § Though there are many classes related to byte streams, the stream classes for file operations are File. Input. Stream and File. Output. Stream. § read method is provided by File. Input. Stream class which will return the next byte in the stream, it will return -1 when it reaches the end of the stream. § write method is provided by File. Output. Stream class which will write one byte of the data into the stream. Unit – 8 : IO Programming 3 Darshan Institute of Engineering & Technology
Example of Byte Steams import java. io. *; public class Copy. File { public static void main(String args[]) throws IOException { File. Input. Stream in = null; File. Output. Stream out = null; try { in = new File. Input. Stream("input. txt"); out = new File. Output. Stream("output. txt"); int c; while ((c = in. read()) != -1) { out. write(c); } } finally { if (in != null) { in. close(); } if (out != null) { out. close(); } }
Character Streams § Java Byte streams are used to perform input and output of 8 -bit bytes, where as Java Character streams are used to perform input and output for 16 -bit unicode. § Though there are many classes related to character streams, the Stream classes used for file operatiosn are. File. Reader and File. Writer. § Though internally File. Reader uses File. Input. Stream and File. Writer uses File. Output. Stream but here major difference is that File. Reader reads two bytes at a time and File. Writer writes two bytes at a time. § We can re-write previous example which makes use of these two classes to copy an input file (having unicode characters) into an output file. Unit – 8 : IO Programming 5 Darshan Institute of Engineering & Technology
Example of Character Steams import java. io. *; public class Copy. File { public static void main(String args[]) throws IOException { File. Reader in = null; File. Writer out = null; try { in = new File. Reader("input. txt"); out = new File. Writer("output. txt"); int c; while ((c = in. read()) != -1) { out. write(c); } } finally { if (in != null) { in. close(); } if (out != null) { out. close(); } }
Standard Streams § All the programming languages provide support for standard I/O where user's program can take input from a keyboard and then produce output on the computer screen. § If you are aware if C or C++ programming languages, then you must be aware of three standard devices STDIN, STDOUT and STDERR. Similar way Java provides following three standard streams. • Standard Input: This is used to feed the data to user's program and usually a keyboard is used as standard input stream and represented as System. in. • Standard Output: This is used to output the data produced by the user's program and usually a computer screen is used to standard output stream and represented as System. out. • Standard Error: This is used to output the error data produced by the user's program and usually a computer screen is used to standard error stream and represented as System. err. Unit – 8 : IO Programming 7 Darshan Institute of Engineering & Technology
Reader § The Java Reader class is the base class of all Reader's in the Java IO API. Subclasses include a Buffered. Reader, Pushback. Reader, Input. Stream. Reader, String. Reader and several others. § Here is a simple Java IO Reader example: Reader reader = new File. Reader("c: \data\myfile. txt"); int data = reader. read(); while (data != -1) { char data. Char = (char) data; data = reader. read(); } § Combining Readers with Input. Stream Reader reader = new Input. Stream. Reader("c: \data\myfile. txt"); Unit – 8 : IO Programming 8 Darshan Institute of Engineering & Technology
Writer § The Java Writer class is the base class of all Writers in the Java IO API. Subclasses include Buffered. Writer and Print. Writer among others. § Here is a simple Java IO Writer example: Writer writer = new File. Writer("c: \data\file-output. txt"); writer. write("Hello World Writer"); writer. close(); § Combining Readers With Output. Streams Writer writer = new Output. Stream. Writer("c: \data\file-output. txt"); Unit – 8 : IO Programming 9 Darshan Institute of Engineering & Technology
File class § Java File class represents the files and directory pathnames in an abstract manner. This class is used for creation of files and directories, file searching, file deletion etc. § The File object represents the actual file/directory on the disk. Below given is the list of constructors to create a File object. Sr. Constructor 1 File(String pathname) This constructor creates a new File instance by converting the given pathname string into an abstract pathname. 2 File(String parent, String child) 3 File(File parent, String child) This constructor creates a new File instance from a parent abstract pathname and a child pathname string. 4 File(URI uri) Unit – 8 : IO Programming 10 Darshan Institute of Engineering & Technology
Methods of File Class Sr. Method 1 public boolean is. Absolute() Tests whether this abstract pathname is absolute. Returns true if this abstract pathname is absolute, false otherwise 2 public String get. Absolute. Path() Returns the absolute pathname string of this abstract pathname. 3 public boolean can. Read() Tests whether the application can read the file denoted by this abstract pathname. Returns true if and only if the file specified by this abstract pathname exists and can be read by the application; false otherwise. 4 public boolean can. Write() Tests whether the application can modify to the file denoted by this abstract pathname. Returns true if and only if the file system actually contains a file denoted by this abstract pathname and the application is allowed to write to the file; false otherwise. 5 public boolean exists() Tests whether the file or directory denoted by this abstract pathname exists. Returns true if and only if the file or directory denoted by this abstract pathname exists; false otherwise Unit – 8 : IO Programming 11 Darshan Institute of Engineering & Technology
Methods of File Class (Cont. ) Sr. Method 6 public boolean is. Directory() Tests whether the file denoted by this abstract pathname is a directory. Returns true if and only if the file denoted by this abstract pathname exists and is a directory; false otherwise. 7 public boolean is. File() Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria 8 public long last. Modified() Returns the time that the file denoted by this abstract pathname was last modified. Returns a long value representing the time the file was last modified, measured in milliseconds since the epoch (00: 00 GMT, January 1, 1970). 9 public long length() Returns the length of the file denoted by this abstract pathname. 10 public boolean delete() Deletes the file or directory. 11 public String[] list() Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname. Unit – 8 : IO Programming 12 Darshan Institute of Engineering & Technology
File. Output. Stream § Java File. Output. Stream is an output stream for writing data to a file. § If you have to write primitive values then use File. Output. Stream But for character-oriented data, prefer File. Writer. § But you can write byte-oriented as well as character-oriented data. JAVA APPLICATION Unit – 8 : IO Programming 101101 …. 13 FILE -----------f. txt Darshan Institute of Engineering & Technology
Methods of File. Output. Steam Sr. Method 1 void write(byte[] b) This method writes b. length bytes from the specified byte array to this file output stream. 2 void write(byte[] b, int off, int len) This method writes len bytes from the specified byte array starting at offset off to this file output stream. 3 void write(int b) This method writes the specified byte to this file output stream. 4 void close() This method closes this file output stream and releases any system resources associated with this stream. Unit – 8 : IO Programming 14 Darshan Institute of Engineering & Technology
Example (File. Output. Stream) class File. Out. Demo { public static void main(String args[]) { try { File. Output. Stream fout = new File. Output. Stream("abc. txt"); String s = "Sourav Ganguly is my favorite player"; byte b[] = s. get. Bytes(); fout. write(b); fout. close(); System. out. println("success. . . "); } catch (Exception e) { System. out. println(e); } } } Unit – 8 : IO Programming 15 Darshan Institute of Engineering & Technology
File. Input. Stream § Java File. Input. Stream class obtains input bytes from a file. § It is used for reading streams of raw bytes such as image data. § For reading streams of characters, consider using File. Reader. § It should be used to read byte-oriented data for example to read image, audio, video etc. JAVA APPLICATION Unit – 8 : IO Programming 101101 …. 16 FILE -----------f. txt Darshan Institute of Engineering & Technology
Methods of File. Input. Steam Sr. Method 1 public int read() the next byte of data, or -1 if the end of the file is reached. 2 public int read(byte[] b) b - the buffer into which the data is read. Returns: the total number of bytes read into the buffer, or -1. 3 public int read(byte[] b, int off, int len) b - the buffer into which the data is read. off - the start offset in the destination array b len - the maximum number of bytes read. Returns: the total number of bytes read into the buffer, or -1 4 public long skip(long n) n - the number of bytes to be skipped. Returns: the actual number of bytes skipped. 5 public int available() an estimate of the number of remaining bytes that can be read 6 public void close() Closes this file input stream and releases any system resources associated. Unit – 8 : IO Programming 17 Darshan Institute of Engineering & Technology
Example (File. Input. Stream) class Simple. Read { public static void main(String args[]) { try { File. Input. Stream fin = new File. Input. Stream("abc. txt"); int i = 0; while ((i = fin. read()) != -1) { System. out. println((char) i); } fin. close(); } catch (Exception e) { System. out. println(e); } } } Unit – 8 : IO Programming 18 Darshan Institute of Engineering & Technology
Input. Stream. Reader § An Input. Stream. Reader is a bridge from byte streams to character streams. § It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform’s default charset may be accepted. Sr. Constructor 1 Input. Stream. Reader(Input. Stream in) Creates an Input. Stream. Reader that uses the default charset. 2 Input. Stream. Reader(Input. Stream in, Charset cs) creates an Input. Stream. Reader that uses the given charset. 3 Input. Stream. Reader(Input. Stream in , String charset. Name) Creates an Input. Stream. Reader that uses the named charset Unit – 8 : IO Programming 19 Darshan Institute of Engineering & Technology
Methods of Input. Stream. Reader Sr. Method 1 int read() This method reads a single character. 2 int read(char[] cbuf, int offset, int length) cbuf − Destination character buffer. offset − Offset at which to start storing characters. length − Maximum numbers of characters to read. The method returns the number of characters read, else -1 if the end of the stream has been reached. 3 boolean ready() This method tells whether this stream is ready to be read. 4 void close() This method closes this file and releases any system resources associated with this Reader. Unit – 8 : IO Programming 20 Darshan Institute of Engineering & Technology
Output. Stream. Writer § An Output. Stream. Writer is a bridge from byte streams to character streams. § Characters written to it are encoded into bytes using a specified charset. Sr. Constructor 1 Output. Stream. Writer(Output. Stream out) This creates an Output. Stream. Writer that uses the default character encoding. 2 Output. Stream. Writer(Output. Stream out, Charset cs) This creates an Output. Stream. Writer that uses the given charset. 3 Output. Stream. Writer(Output. Stream out, String charset. Name) This creates an Output. Stream. Writer that uses the named charset. Unit – 8 : IO Programming 21 Darshan Institute of Engineering & Technology
Methods of Output. Stream. Writer Sr. Method 1 void write(int c) This method writes a single character. 2 void write(String str, int off, int len) off − Offset at which to start storing characters. len − Maximum numbers of characters to write. This method writes a portion of a string. 3 void write(char[] cbuf, int off, int len) This method writes a portion of an array of characters. 4 void flush() This method flushes the stream. 5 void close() This method closes the stream, flushing it first. Unit – 8 : IO Programming 22 Darshan Institute of Engineering & Technology
File. Writer and File. Reader § Java File. Writer and File. Reader classes are used to write and read data from text files (they are Character Stream classes). § It is recommended not to use the File. Input. Stream and File. Output. Stream classes if you have to read and write any textual information as these are Byte stream classes. Unit – 8 : IO Programming 23 Darshan Institute of Engineering & Technology
File. Writer § File. Writer is useful to create a file writing characters into it. • This class inherits from the Output. Stream. Writer class. • File. Writer is meant for writing streams of characters. For writing streams of raw bytes, consider using a File. Output. Stream. Sr. Constructor 1 File. Writer(File file) Constructs a File. Writer object given a File object. 2 File. Writer (File file, boolean append) Constructs a File. Writer object given a File object, it will append if second parameter is true. 3 File. Writer(String file) Constructs a File. Writer object from the path given in parameter. 4 File. Writer (String file, boolean append) Constructs a File. Writer object from the path given, it will append if second parameter is true. Unit – 8 : IO Programming 24 Darshan Institute of Engineering & Technology
File. Writer (Cont. ) Sr. Methods 1 public void write (int c) throws IOException Writes a single character. 2 public void write (char [] stir) throws IOException Writes an array of characters. 3 public void write(String str)throws IOException Writes a string 4 public void write(String str, int off, int len)throws IOException Writes a portion of a string. Here off is offset from which to start writing characters and len is number of character to write. Unit – 8 : IO Programming 25 Darshan Institute of Engineering & Technology
File. Reader § File. Reader is useful to read data in the form of characters from a ‘text’ file. • This class inherit from the Input. Stream. Reader Class. • File. Reader is meant for reading streams of characters. For reading streams of raw bytes, consider using a File. Input. Stream Sr. Constructor 1 File. Reader(File file) Creates a File. Reader , given the File to read from. 2 File. Reader(String file. Name) Creates a new File. Reader , given the name of the file to read from. 3 File. Reader(File. Descripter fd) Creates a new File. Reader , given the File. Descripter to read from. Unit – 8 : IO Programming 26 Darshan Institute of Engineering & Technology
File. Reader (Cont. ) Sr. Methods 1 public int read () throws IOException Reads a single character. This method will block until a character is available, an I/O error occurs, or the end of the stream is reached. 2 public int read(char[] cbuff) throws IOException Reads characters into an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached. 3 public abstract int read(char[] buff, int off, int len) throws IOException Reads characters into a portion of an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached. Parameters: cbuf – Destination buffer off – Offset at which to start storing characters len – Maximum number of characters to read 4 public long skip(long n) throws IOException Skips characters. This method will block until some characters are available, an I/O error occurs, or the end of the stream is reached. Unit – 8 : IO Programming 27 Darshan Institute of Engineering & Technology
Example File. Reader/File. Writer import java. io. *; public class Copy. File { public static void main(String args[]) throws IOException { File. Reader in = null; File. Writer out = null; try { in = new File. Reader("input. txt"); out = new File. Writer("output. txt"); int c; while ((c = in. read()) != -1) { out. write(c); } } finally { if (in != null) { in. close(); } if (out != null) { out. close(); } }
Buffered. Reader § The Java. io. Buffered. Reader class reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. Following are the important points about Buffered. Reader: • The buffer size may be specified, or the default size may be used. • Each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. Sr. Constructor 1 Buffered. Reader(Reader in) This creates a buffering character-input stream that uses a default-sized input buffer. 2 Buffered. Reader(Reader in, int sz) This creates a buffering character-input stream that uses an input buffer of the specified size. Unit – 8 : IO Programming 29 Darshan Institute of Engineering & Technology
Buffered. Reader (Cont. ) Sr. Methods 1 void close() This method closes the stream and releases any system resources associated with it. 2 int read() This method reads a single character. 3 int read(char[] cbuf, int off, int len) This method reads characters into a portion of an array. 4 String read. Line() This method reads a line of text. 5 void reset() This method resets the stream. 6 long skip(long n) This method skips characters. Unit – 8 : IO Programming 30 Darshan Institute of Engineering & Technology
Buffered. Reader (Example) import java. io. Buffered. Reader; import java. io. File. Reader; import java. io. IOException; class Buffered. Reader. Demo { public static void main(String[] args) throws IOException { File. Reader fr = new File. Reader("input. txt"); Buffered. Reader br = new Buffered. Reader(fr); char c[] = new char[20]; br. skip(8); if (br. ready()) { System. out. println(br. read. Line()); br. read(c); for (int i = 0; i < 20; i++) { System. out. print(c[i]); } } Unit – 8 : IO Programming 31 Darshan Institute of Engineering & Technology
- Slides: 31