Java Reference
In-Depth Information
ues, including all of Java's built-in types. Suppose that you want to write a binary integer
plus a binary floating-point value into a file and read it back later. This code shows the writ-
ing part:
public
public class
class WriteBinary
WriteBinary {
public
public static
static void
void main ( String [] argv ) throws
throws IOException {
int
int i = 42 ;
double
double d = Math . PI ;
String FILENAME = "binary.dat" ;
DataOutputStream os = new
new DataOutputStream (
new FileOutputStream ( FILENAME ));
os . writeInt ( i );
os . writeDouble ( d );
os . close ();
System . out . println ( "Wrote " + i + ", " + d + " to file " + FILENAME );
new
}
}
The reading part is left as an exercise for the reader. Should you need to write all the fields
from an object, you should probably use one of the methods described in Saving and Restor-
ing Java Objects .
Seeking to a Position within a File
Problem
You need to read from or write to a particular location in a file, such as an indexed file.
Solution
Use a RandomAccessFile .
Discussion
The class java.io.RandomAccessFile allows you to move the read or write position when
writing to any location within a file or past the end. This allows you to create or access “files
with holes” on some platforms and lets you read or write indexed or other database-like files
in Java. The primary methods of interest are void seek(long where) , which moves the po-
Search WWH ::




Custom Search