150 likes | 256 Views
Top IO Hierarchy. Input Stream. Output Stream. Reader. Writer. Streams. InputStream Reader. BufferedReader std in = new BufferedReader ( new InputStreamReader ( System.in ) );. System.in is an object of InputStream. PrintWriter out = new PrintWriter ( new BufferedWriter (
E N D
InputStreamReader BufferedReaderstdin =new BufferedReader( new InputStreamReader( System.in ) ); System.in is an object of InputStream
PrintWriterout =new PrintWriter( new BufferedWriter( newFileWriter (“foo.out” ) ) ); Note: System.out and System.err are PrintWriter objects FileReader & FileWriter BufferedReaderin =new BufferedReader( new FileReader ( “foo.in” ) );
Reading from binary file FileInputStream fis = new FileInputStream(myFileObj); ObjectInputStream ois = new ObjectInputStream(fis); int i = ois.readInt(); String today = (String) ois.readObject(); Date date = (Date) ois.readObject(); ois.close();
How to tell end of file try { read from file } catch ( EOFException endOfFileException ) { do what you need to do when end of file is reached } Other ways possible. This is the recommended method.
Writing to binary file FileOutputStream fos = new FileOutputStream(myFileObj); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeInt(12345); oos.writeObject("Today"); oos.writeObject(new Date()); oos.close();
Reading from text file BufferedReader input = new BufferedReader( new FileReader( myFile ) ); String text = input.readLine(); input.read(myCharArray, off, len); input.close();
Writing to text file BufferedWriter output = new BufferedWriter( new FileWriter( myFile ) ); String text = “hello \n”; output.write(text); output.write(myCharArray,off,len); output.flush() ; output.close();
0 100 200 300 400 500 byte offsets 100 bytes 100 bytes 100 bytes 100 bytes 100 bytes 100 bytes Random Access Files • Use fixed length for every record • Easy to calculate record locations
Random Access File Methods RandomAccessFile raFile = new RandomAccessFile( fileObj, "rw" ); raFile.seek( ( recordNumber - 1 ) * RandomAccessAccountRecord.SIZE ); raFile.writeInt( 12345 ); raFile.writeDouble( getBalance() ); raFile.writeChars( buffer.toString() ); int i = raFile.readInt(); double d = raFile.readDouble(); char c = raFile.readChar(); raFile.close();