File truy cập ngẫu nhiên (Random Access Files)

Bên cạnh việc xử lý xuất nhập trên file theo kiểu tuần tự thông qua các luồ ng, java cũng hỗ trợ truy cập ngẫu nhiên nội dung của một file nào đó dùng RandomAccessFile. RandomAccessFile không dẫn xuất từ InputStream hay OutputStream mà nó hiện thực các interface DataInput, DataOutput (có định nghĩa các phương thức I/O cơ bản). RandomAccessFile hỗ trợ vấn đề định vị con trỏ file bên trong một file dùng phương thức seek(long newPos).

Ví dụ: minh họa việc truy cập ngẫu nhiên trên file. Chương trình ghi 6 số kiểu double xuống   file, rồi đọc lên theo thứ   tự ngẫu nhiên.

import java.io. *; class RandomAccessDemo {

public static void main(String args[]) throws IOException {

double data[] = {19.4, 10.1, 123.54, 33.0, 87.9, 74.25}; double d;

RandomAccessFile raf;

try

{

raf = new RandomAccessFile(“D:\\random.dat”, “rw”);

}

catch(FileNotFoundException exc)

{

System.out.println(“Cannot open file. “); return;

}

 

// Write values to the file. for(int i=0; i < data.length; i++)

{

try

{

raf. writeDouble(data[i]);

}

catch(IOException exc)

{

System.out.println(“Error writing to file. “); return;

}

try

{

// Now, read back specific values raf.seek(O); // seek to first double d = raf.readDouble();

System.out.println(“First value is ” + d); raf.seek(8); // seek to second double d = raf.readDouble(); System.out.println(“Secondvalue is ” + d); raf.seek(8 * 3); // seek to fourth double d = raf.readDouble();

System.out.println(“Fourth value is ” + d); System. out.println();

// Now, read every other value. System.out.println(“Here is every other value: “); for(int i=0; i < data.length; i+=2)

{ raf.seek(8 * i); // seek to ith double d = raf.readDouble();

System.out.print(d + ” “);

}

catch(IOException exc)

{

System.out.println(“Error seeking or reading. “);

} raf.close();

}

}

Kết quả: