You are on page 1of 31

Files & IO

• At its lowest level, all Java I/O involves a stream of bytes either entering or leaving memory Packaged classes exist to make it easy for a program to read and write larger units of data. Low-level stream class object are used to handle byte I/O

High-level stream class object will allow the program to read and write primitive data values and objects

File Classes
– – – – – Java views the data in files as a stream of bytes. A stream of bytes from which data are read is called an input stream. A stream of bytes to which data are written is called an output stream. Java provides classes for connecting to and manipulating data in a stream. The classes are defined in the package and are organized in a large complex hierarchy.

Input/Output Situations

Serialization and Object Streams Serialization allows objects to be converted to a sequence of bytes The sequence of bytes can be stored in a file, database, sent to a remote machine etc. The sequence of bytes can be used to recreate the original object

Java provides methods for reading and writing complete objects. – This makes it easy to save a program's state before closing it and to restore the state when the program is run again. – Objects that are saved between executions of a program are said to be persistent. – The process of writing them to and reading them from a file is called serialization

• Serializing
– Creating the sequence of bytes from an object

• Deserializing
– Recreating the object from the above generated bytes

creates a new object with the fields containing the same values as the original object ,If the fields are also serializable objects then they are also "recreated"

• A Serializable class must:
– Implement the interface

– Identify the fields that should be serializable

• •

Using the default method all fields are identified as serializable by default, unless marked transient. Have access to the no-argument (or default) constructor of its first nonserializable superclass (or supersuperclass, supersupersuper class) When an object is deserialized, its constructors are not called.

• •

Customizing Deserialization
• The readObject() method allows to customize the deserialization of an object

• • • • • • • •

The readObject() must have the signature given below readObject must be implemented in the class of the object to be deserialized private void readObject( ObjectInputStream in) { // this is normally called first in.defaultReadObject(); //Now you do the custom work }

readObject/writeObject & Inheritance
• Parent is Serializable
– Parents fields will be serialized/deserialized automatically.

Parent is not serializable
– The parents no-argument constructor will be called to initialize the object.

– If you wish the parent’s fields to the reset to the proper values you need to do it in the child’s write/readObject method.

Class serialVersionUID
• • Java generates a serialVersionUID for each class When deserializing an object, the serialVersionUID of the deserialized object and it class are checked If they do not agree, an exception is thrown Information used to Compute the serialVersionUID 1.Class name 2. The class modifiers 3. The name of each interface 4. For each field of the class(except private static and private transient fields),The name of the field ,the modifiers of the field ,The descriptor of the field For each method including constructors, except private methods and constructors,The name of the method ,The modifiers of the method ,The descriptor of the method

• •

Input/Output Situations
•  

To use serialization : Make classes implement the serializable interface. Write objects using an ObjectOutputStream and read them later using an ObjectInputStream. A class-scope variable can be declared as transient , meaning that it is ignored during serialization.

Classes in I/O Package
• File:
– This is an abstract representation file and directory pathnames – Not used to read and write data – Used for searching and deleting of files, creating directories and working with path and making directories

– Used to read characters from files – The read() method of this class is used to read characters – These are wrapped by BufferedReader to improve the performance

– Used to write character to files – The Write method() of this classes is used to write characters – Wrapped by BufferedWriter to improve the performance

Classes in I/O Package
• BufferedReader
– – – – It helps in efficent reading of files Reads a large amount of data from a file at once and keep that data in buffer Minimizes the number of times of file access. Provides a readLine() method , which reads a line of characters from the file

– Provides a newLine() method , which that creates line separators automatically

– Provides number of flexible and powerful methods to write data to files – Methods like format(),printf() and append() are used to work with data – Method like print() or println() of this class take a single parameter of any data type – PrintWriter wraps the FileWriter – The resulting file can be read with a text editor or an input stream reader.

Handling file input and output
• Files with Viewed and Created with Text Editors or when the type of data is unknown
– use a print writer for output – stream tokenizer for input

When not Using Text Editors and the data type is known
– use a data input stream for input – a data output stream for output

File Input

Reading Data from a Text File contains nothing but characters. – Java provides several ways to read characters from a file: • one character at a time, using the class InputStreamReader • one word at a time, using the class StreamTokenizer • one line at a time, using the class BufferedReader – To utilize the desired type of input, the Java programmer uses the appropriate class and methods.

import*; public class PrintWriterTest { public static void main(String args[]) { try { PrintWriter out = new PrintWriter(new FileWriter("myAccount2.dat")); out.println("srivatsan"); out.println("10099"); out.println(5000); out.close(); } catch (FileNotFoundException e) { System.out.println("Error: Cannot open file for writing."); } catch (IOException e) { System.out.println("Error: Cannot write to file."); } } }

class BufferedReader
• Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
– BufferedReader in = new BufferedReader(new FileReader(“file.txt")); – Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.

FileReader are meant for reading streams of characters

File Class
• • The File class can be used to retrieve information from a file or directory. The class is simply used as a toolkit to get information about files and directories. it is a utility class that:
– has methods for getting file/directory info. – cannot be used to read or write to a file.

To make a File object, there are three commonly used constructors File
– File file1 = new File("C:\\Data\\myFile.dat"); File file2 = new File("C:\\Data\\", "myFile.dat"); – File file3 = new File(new File("."), "myFile.dat");

Stream Hirearchy

Example for File Input Stream
import*; public class FileInputStreamTest { public static void main(String args[]) { try { FileInputStream in = new FileInputStream("myFile.dat"); while(in.available() > 0) System.out.print( (char) + " "); in.close(); } catch (FileNotFoundException e) { System.out.println("Error: Cannot open file for reading."); } catch (EOFException e) { System.out.println("Error: EOF encountered, file may be corrupted."); } catch (IOException e) { System.out.println("Error: Cannot read from file."); } } }

OutputStream Class
• • The streams in this hierarchy are responsible for outputting data in the form of bytes or data types. OutputStreams have a write() method to output a byte of data at a time.


• • • • • The streams in this hierarchy are responsible for outputting binary data. OutputStreams have a write() method that allows us to output a byte of data at a time. To open a file, create an instance of a FileOutputStream using one of the following constructors: Opening a file for reading or writing may generate a reading or writing to/from a file may generate a

Example of File output Stream
• import*; public class FileOutputStreamTest { public static void main(String args[]) { try { FileOutputStream out = new FileOutputStream("myFile.dat"); out.write('H'); out.write(69); out.write(76); out.write('L'); out.write('O'); out.write('!'); out.close(); } catch (FileNotFoundException e) { System.out.println("Error: Cannot open file for writing."); } catch (IOException e) { System.out.println("Error: Cannot write to file."); } } }


Buffered Reader
import*; public class BufferedReaderTest { public static void main(String args[]) { try { FileReader filereader = new FileReader("myAccount2.dat"); BufferedReader bufferedreader = new BufferedReader(filereader); String instring; while((instring = bufferedreader.readLine()) != null) { System.out.println(instring); } filereader.close();

• It support binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) as well as String values. All data streams implement either the Data Input interface or the Data Output interface. out.writeDouble(); out.writeInt(); out.writeUTF()

• • •

Random access files
• • • • It permit nonsequential, or random, access to a file's contents The class implements both the DataInput and DataOutput interfaces and therefore can be used for both reading and writing To Read the file
– new RandomAccessFile(“filename.txt", "r");

To open for both reading and writing:
– new RandomAccessFile("xanadu.txt", "rw");

• • •

It supports the notion of a file pointer, which indicates the current location in the file. When the file is first created, the file pointer is set to 0, Calls to the read and write methods adjust the file pointer by the number of bytes read or written.

Random Access File
• • • • IThe three methods for explicitly manipulating the file pointer. int skipBytes(int)
– Moves the file pointer forward the specified number of bytes

void seek(long)
– – Positions the file pointer just before the specified byte Returns the current byte location of the file pointer

long getFilePointer()

The StreamTokenizer class
• • The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time. Each character can have zero or more of these attributes
• • nextToken() Parses the next token from the input stream of the tokenizer. The type of the next token is returned in the ttype field.

• • •

ttype After a call to the nextToken method, this field contains the type of the token just read. For a single character token, its value is the single character,
• • • • TT_WORD indicates that the token is a word. TT_NUMBER indicates that the token is a number. TT_EOL indicates that the end of line has been read. The field can only have this value if the eolIsSignificant method has been called with the argument true. TT_EOF indicates that the end of the input stream has been reached.


Stream Tokenizer
– – To Look for patterns in an Input Stream Stream Tokenizer The method nextToken() reads the next token from the input stream and updates the tokenizer's instance variables with information about the type and value of the token.

TT_EOF - denotes end of stream has been read TT_WORD - denotes a word token has been read import*; class Example_8 { public static void main(String args[]) throws Exception { FileReader filereader = new FileReader("file.txt"); StreamTokenizer streamtokenizer = new StreamTokenizer(filereader); String instring; /while(streamtokenizer.nextToken() != StreamTokenizer.TT_EOF) { if(streamtokenizer.ttype == StreamTokenizer.TT_WORD) System.out.println(streamtokenizer.sval); } filereader.close(); }}

• • • • The Formatter class of java.util provides formatter methods These methods can be called as part of printf Methods They are called as static.format() method and passed with arguments\ Its invoked as (formatting_Instructions,number_to_ format);

– String s = String.format(“%, d”, 100000000);

– System.out.println(s);
– The second argument is formatted as a decimal Integer and inserted with commas.

• • •

Can use a % , to indicate the argument and format that has to be used for it %[argument number] [flags] [width] [.precision] type format(“%,6.1f”,42.00);

Format Type
• • • • • • • • • • • • • Type is Mandatory and rest are all optional Format(“%d”,56); Format(“%.3f”,42.00); Multiple Arguments Int a = 3434; Double b =45563.8992349d; String s =String.format(“the number is %,d out %.2f”,a,b); Flags - Used to Left Justify + To Indicate (+ or -) with the argument 0 pad with 0’s , Use to specify comma separator ( Used to enclose negative number with parentheses