文件存取通常是顺序的,每在文件中存取一次,文件的读取位置就会相对于目前的位置前进一次。然而有时必须指定文件的某个区段进行读取或写入的动作,也就是进行随机存取(Random Access),即要能在文件中随意地移动读取位置。这时可以使用RandomAccessFile,使用它的seek()方法来指定文件存取的位置,指定的单位是字节。
为了移动存取位置时的方便,通常在随机存取文件中会固定每一个数据的长度。例如长度固定为每一个学生个人数据,Java中并没有直接的方法可以写入一个固定长度数据(像C/C++中的structure),所以在固定每一个长度方面必须自行设计。先设计一个学生数据的类。
对于每一个学生数据的实例在写入文件时,会固定以34字节的长度写入,也就是15个字符(30字节)加上一个int整数的长度(4字节)。
使用StringBuilder来固定字符长度,可以使用size()方法来取得长度信息。
package io;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Scanner;
/**
*
* @author HaoWang
*/
public class TestRandomAccessFile {
public static void main(String[] args) {
Student[] students = {
new Student("Justin", 90),
new Student("momor", 95),
new Student("Bush", 88),
new Student("caterpillar", 84)};
try {
File file = new File("C:\\a.txt");// 建立RandomAccessFile实例并以读写模式打开文件
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
for(int i = 0; i < students.length; i++) {
// 使用对应的write方法写入数据
randomAccessFile.writeChars(students[i].getName());
randomAccessFile.writeInt(students[i].getScore());
}
Scanner scanner = new Scanner(System.in);
System.out.print("读取第几个数据?");
int num = scanner.nextInt();
// 使用seek()方法操作存取位置
randomAccessFile.seek((num-1) * Student.size());
Student student = new Student();
// 使用对应的read方法读出数据
student.setName(readName(randomAccessFile));
student.setScore(randomAccessFile.readInt());
System.out.println("姓名:" + student.getName());
System.out.println("分数:" + student.getScore());
// 设置关闭文件
randomAccessFile.close();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("请指定文件名称");
} catch(IOException e) {
System.out.println(e.toString());
}
}
private static String readName(RandomAccessFile randomAccessfile)
throws IOException {
char[] name = new char[15];
for (int i = 0; i < name.length; i++) {
name[i] = randomAccessfile.readChar();
}
// 将空字符取代为空格符并返回
return new String(name).replace('\0', ' ');
}
}
class Student {
private String name;
private int score;
public Student() {
this("No name",0);
}
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public void setName(String name) {
StringBuilder builder = null;
if (name != null) {
builder = new StringBuilder(name);
} else {
builder = new StringBuilder(15);
}
builder.setLength(15); // 最长 15 字符
this.name = builder.toString();
}
public void setScore(int score) {
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
// 每个数据固定写入34字节
public static int size() {
return 34;
}
}