RandomAccessFile类 支持"随机访问"
文件可以不用从头开始访问,可以选择开始访问的位置。
有可以指示读取位置的文件指示器、游标。
↓可以选择位置
#########################
可以直接跳过前面的数据流,再开始读取。
文件记录采用等长记录格式,每一条记录都是一样长的,每条记录分成若干字段,
记录长度相等使文件可以跳转
可以指定读写方式。
String.substring(0,8) 获取前8个字符; “/u0000”为 空字符串
注意写入时不同的对象所占用的字符大小不同,读取时根据字符调整指针位置
注意write 与 read方法对应使用
测试结果:**************************************
赵钱孙 :320
tom Gree:21
OK :23
*************************************************
代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
public class TestRandomAccessFile {
public static void main(String[] args) throws Exception{
Student s1 = new Student("tom Green",21);
Student s2 = new Student("赵钱孙",320);
Student s3 = new Student("OK",23);
File f = new File("testRandomFile.txt");
RandomAccessFile raf;
raf = new RandomAccessFile(f,"rw");
raf.writeChars(s1.name);
raf.writeInt(s1.age);
raf.writeChars(s2.name);
raf.writeInt(s2.age);
raf.writeChars(s3.name);
raf.writeInt(s3.age);
RandomAccessFile raf1 = new RandomAccessFile(f,"r");
raf1.skipBytes(20);
String str = "";
for(int i=0;i<Student.LEN;i++){
str += raf1.readChar();
}
System.out.print(str+":");
int temp = raf1.readInt();
System.out.println(temp);
str = "";
raf1.seek(0);
for(int i=0;i<Student.LEN;i++){
str += raf1.readChar();
}
System.out.print(str+":");
temp = raf1.readInt();
System.out.println(temp);
str = "";
raf1.skipBytes(20);
for(int i=0;i<Student.LEN;i++){
str += raf1.readChar();
}
System.out.print(str+":");
temp = raf1.readInt();
System.out.println(temp);
}
}
public class Student {
String name = null;
int age = 0;
public static final int LEN = 8;
public Student(String name, int age) {
if(name.length()>LEN){
name = name.substring(0, 8);
}
else {
while(name.length()<LEN){
name += " ";
}
}
this.name = name;
this.age = age;
}
}