1, 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).
2, Ví dụ:
Bài này lý thuyết ngắn, nhưng ví dụ hơi dài, chủ yếu là đọc code để hiểu!
Chương trình sau sẽ ghi 9 số kiểu double xuống file, rồi đọc lên theo thứ tự ngẫu nhiên. Các bạn xem code có chỗ nào không hiểu cứ bình luận phía dưới, mọi người cùng nhau giải quyết! ^^
PHP:
package javaandroidvn;
import java.io.*;
class JavaAndroidVn {
public static void main(String args[]) throws IOException {
double data[] = {11.2, 13.6, 255.6, 117.92, 2007.96, 8.9, 9.9, 10.0, 100.6};
double d;
RandomAccessFile raf;
try {
raf = new RandomAccessFile("E:\\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(0 * 8); // seek to first double
d = raf.readDouble();
System.out.println("First value is " + d);
raf.seek(8 * 1); // seek to second double
d = raf.readDouble();
System.out.println("Second value is " + d);
raf.seek(8 * 3); // seek to fourth double
d = raf.readDouble();
System.out.println("Fourth value is " + d);
System.out.println();
//Read All data
System.out.println("Read all: ");
for (int i = 0; i < data.length; i++) {
raf.seek(8 * i); // seek to ith double
d = raf.readDouble();
System.out.print(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 + " ");
}
System.out.println("\n");
} catch (IOException exc) {
System.out.println("Error seeking or reading.");
}
raf.close();
}
}
Không có nhận xét nào:
Đăng nhận xét