Random file access in Java
Objectives
- use binary file I/O in Java
Binary file I/O
- Need to use: import java.io.*;
- Remember to catch exceptions on all file I/O operations or specify
that the enclosing method throws that exception.
- We have two good choices for dealing with binary files easily:
- open a FileInputStream or FileOutputStream and wrap it in
a DataInputStream or DataOutputStream - good for sequential access
binary data
- open a RandomAccessFile - this is good when you want to jump around
a file or read and write a file - it implements DataInput and DataOutput
(like DataInputStream and DataOutputStream do)
- See the Java API documentation for
DataInputStream,
DataOutputStream, and
RandomAccessFile
- The DataInput interface declares methods for reading the basic data types,
such as readInt(), readDouble(), and readBoolean(). It also declares the method
readLine() to read a whole line of input at once.
- The DataOutput interface declares methods for writing the basic data types,
such as writeInt(), writeDouble(), and writeBoolean(). It also declares the method
writeChars() to send a String to output.
- Remember to close (close() method) files when you are done using them.
- See Binary01.java: writes and then reads binary data in a file
- See Binary02.java: writes and then reads binary data in a file using a class for the record to make life easier
- See CreateData02.java: program used to create binary data file from a text file with population data
- See RandomTest.java: demonstrates random access file techniques
- See RandomTest2.java: variation of RandomTest.java that
converts Unicode characters to byte values to save space