150 likes | 260 Vues
This guide covers the essentials of file handling in Java, focusing on reading from and writing to both text and binary files. Learn how to use BufferedReader and BufferedWriter for text files and ObjectInputStream and ObjectOutputStream for binary files. Understand how to properly handle end-of-file exceptions, create random access files, and perform read/write operations efficiently. This overview includes practical code snippets to help you implement these techniques in your Java applications, ensuring optimal file manipulation.
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();