Binary03.java
Select all
/* Binary03.java David Klick 2005-01-26 Writes and then reads binary data in a file. This program demonstrates how to seek to a particular record. */ import java.io.*; class MyRecord { public int n; public double x, y, z; public final int SIZE = 28; public void write(RandomAccessFile f, int recno) throws IOException { f.seek(recno * SIZE); f.writeInt(n); f.writeDouble(x); f.writeDouble(y); f.writeDouble(z); } public void read(RandomAccessFile f, int recno) throws IOException { f.seek(recno * SIZE); n = f.readInt(); x = f.readDouble(); y = f.readDouble(); z = f.readDouble(); } public String toString() { return "n = " + n + ", x = " + x + ", y = " + y + ", z = " + z; } } public class Binary03 { public static void main(String[] args) throws IOException { String filename = "Binary02.dat"; RandomAccessFile file = new RandomAccessFile(filename, "rw"); MyRecord tmp = new MyRecord(); // initialize array of records for (int i=0; i<10; i++) { tmp.n = i * 2; tmp.x = i * 1.1; tmp.y = i * 2.2; tmp.z = 100.0 - i * 3.3; tmp.write(file, i); } // read data from file System.out.println("Data read from file:"); for (int i=0; i<10; i++) { tmp.read(file, i); System.out.println(i + ": " + tmp); } file.close(); } }