// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.RandomAccessFile;

public class Seek {
    private static final int RECSIZ = 4;
    private static final String FNM = "javax.fix";
    private static long recno(int ix) {
        return (ix - 1) * RECSIZ;
    }
    private static int eof = 0;
    private static final byte[] ZERO = new byte[RECSIZ];
    public static void testWriteOne(RandomAccessFile raf, int ix, String buf) throws IOException {
        if(ix > eof + 1) {
            raf.seek(recno(eof + 1));
            for(int i = eof + 1; i < ix; i++) {
                raf.write(ZERO);
            }
            eof = ix;
        }
        raf.seek(recno(ix));
        raf.write(buf.getBytes());
    }
    public static void testWrite() throws IOException {
        RandomAccessFile raf = new RandomAccessFile(FNM, "rw");
        testWriteOne(raf, 3, "CCCC");
        testWriteOne(raf, 2, "BBBB");
        testWriteOne(raf, 1, "AAAA");
        raf.close();
    }
    public static void testReadSequential() throws IOException {
        InputStream is = new FileInputStream(FNM);
        byte[] buf = new byte[RECSIZ+1]; // will read a fictive LF
        while(is.read(buf) > 0) {
            String s = new String(buf, 0, RECSIZ);
            System.out.printf("|%s| %d\n", s, s.length());
        }
        is.close();
    }
    public static void testReadRandomOne(RandomAccessFile raf, int ix) throws IOException {
        raf.seek(recno(ix));
        byte[] buf = new byte[RECSIZ];
        raf.read(buf);
        String s = new String(buf);
        System.out.printf("|%s| %d\n", s, s.length());
    }
    public static void testReadRandom() throws IOException {
        RandomAccessFile raf = new RandomAccessFile(FNM, "rw");
        testReadRandomOne(raf, 3);
        testReadRandomOne(raf, 2);
        testReadRandomOne(raf, 1);
        raf.close();
    }
    public static void main(String[] args) throws Exception {
        System.out.println("Java seek");
        testWrite();
        testReadSequential();
        testReadRandom();
    }
}
