/* an simple example to show some RandomAccessFile methods in action: generate a RandomAccessFile comprising random doubles, then read them back in an sum up sequentially and in random order, both twice ... */ import java.nio.*; import java.nio.channels.*; import java.util.*; import java.io.IOException; import java.io.RandomAccessFile; public class RandomAccessFileTest { public static void main(String[] args) throws Exception { long before = System.currentTimeMillis(); int numRows = Integer.parseInt(args[0]); int seed = Integer.parseInt(args[1]); int k = 1000; System.out.println("generating " + numRows + " rows with " + k + " doubles, seed = " + seed); RandomAccessFile file = new RandomAccessFile("doubles","rw"); Random r = new Random(seed); double sum = 0.0; for(int i = 0; i < numRows; i++) { for(int j = 0; j < k; j++) { double x = r.nextDouble(); sum += x; file.writeDouble(x); } } long after = System.currentTimeMillis(); System.out.println("finished writing, sum = " + sum + " time " + (after-before)); file.close(); readInOrder(numRows,k); readInRandomOrder(numRows,k,r); readInOrder(numRows,k); readInRandomOrder(numRows,k,r); } public static void readInOrder(int numRows, int k) throws Exception { long before = System.currentTimeMillis(); RandomAccessFile file = new RandomAccessFile("doubles","r"); double sum = 0.0; for(int i = 0; i < numRows; i++) { int base = i * k * 8; for(int j = 0; j < k; j++) { file.seek(base); double x = file.readDouble(); sum += x; base += 8; } } long after = System.currentTimeMillis(); System.out.println("finished reading, sum = " + sum + " time " + (after-before)); file.close(); } public static void readInRandomOrder(int numRows, int k, Random r) throws Exception { List rows = new ArrayList(numRows); for(int i = 0; i < numRows; i++) { rows.add(i); } Collections.shuffle(rows,r); long before = System.currentTimeMillis(); RandomAccessFile file = new RandomAccessFile("doubles","r"); double sum = 0.0; for(Integer row: rows) { int base = row * k * 8; for(int j = 0; j < k; j++) { file.seek(base); double x = file.readDouble(); sum += x; base += 8; } } long after = System.currentTimeMillis(); System.out.println("finished randomR, sum = " + sum + " time " + (after-before)); file.close(); } }