Java中RandomAccessFile类
只能访问文件,不能操作其他io设备
支持随机访问
在读写等长记录文件有优势
实例:
import java.io.*;
class Employee {
private String name;
private int age;
public static final int LEN = 8;
String getName() {
return name;
}
int getAge() {
return age;
}
Employee(String name, int age) {
if (name.length() > LEN) { // 为了构造等长记录
this.name = name.substring(0, LEN-1);
} else {
this.name = name;
while (this.name.length() < LEN) {
this.name += '\u0000';
}
}
this.age = age;
}
}
public class RandomAccessFileTest {
public static void main(String [] args) {
Employee e1 = new Employee("Ronnie", 37);
Employee e2 = new Employee("John", 37);
Employee e3 = new Employee("Mark", 37);
try {
RandomAccessFile randFile = new RandomAccessFile("employee.txt", "rw");
//randFile.write(e1.getName().getBytes()); // 如果name有中文,会出现问题,因为一个英文字符转换为一个字节,一个中文字符转换为两个字节,可以用writeChars函数改写
randFile.writeChars(e1.getName()); //-
randFile.writeInt(e1.getAge());
//randFile.write(e2.getName().getBytes());
randFile.writeChars(e1.getName()); //-
randFile.writeInt(e2.getAge());
//randFile.write(e3.getName().getBytes());
randFile.writeChars(e1.getName()); //-
randFile.writeInt(e3.getAge());
randFile.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
//byte[] nameBuf = new byte[Employee.LEN];
RandomAccessFile randFile = new RandomAccessFile("employee.txt", "r");
//randFile.skipBytes(12);
randFile.skipBytes(20); //-
//int len = randFile.read(nameBuf);
//String name = new String(nameBuf, 0, len);
String name = "";//-
for (int i = 0; i < Employee.LEN; ++i) { //-
name += randFile.readChar(); //-
}//-
System.out.println(name.trim() + ":" + randFile.readInt());
name = ""; //-
randFile.seek(0); // 绝对定位
//len = randFile.read(nameBuf);
//name = new String(nameBuf, 0, len);
for (int i = 0; i < Employee.LEN; ++i) { //-
name += randFile.readChar(); //-
} //-
System.out.println(name.trim() + ":" + randFile.readInt());
name = ""; //-
//randFile.skipBytes(12);
randFile.skipBytes(20); //-
//len = randFile.read(nameBuf);
//name = new String(nameBuf, 0, len);
for (int i = 0; i < Employee.LEN; ++i) { //-
name += randFile.readChar(); //-
} //-
System.out.println(name.trim() + ":" + randFile.readInt());
randFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
注释部分为按字节写入时的程序,带//-为原来的代码
其他函数请参照jdk文档