ITEEDU

Java Gossip: RandomAccessFile

档案存取通常是「循序的」,每在档案中存取一次,读取档案的位置就会相对于目前的位置前进,然而有时候您必须对档案的某个区段进行读取或写入的动作,也就是进行「随机存取」(Random access),也就是说存取档案的位置要能在档案中随意的移动,这时您可以使用RandomAccessFile,使用seek()方法来指定档案存取的位置,指定的单位是字节,藉由它您就可以对档案进行随机存取的动作。

为了方便,通常在随机存取档案时会固定每组资料的长度,例如一组学生个人数据,Java中并没有像C/C++中可以直接写入一个固定长度结构(Structure)的方法,所以在固定每组长度的方面您必须自行设计。

下面这个程序示范了如何使用RandomAccessFile来写入档案,并随机读出一笔您所想读出的资料:

Student.java
package onlyfun.caterpillar;
public class Student {
	private String name; // 固定 15 字符
	private int score;
	public Student() {
		setName("noname");
	}
	public Student(String name, int score) {
		setName(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);
		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;
	}
}
RandomAccessFileDemo.java
package onlyfun.caterpillar;
import java.io.*;
import java.util.*;
public class RandomAccessFileDemo {
	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(args[0]);
			// 建立RandomAccessFile实例并以读写模式开启档案
			RandomAccessFile randomAccessFile =
			new RandomAccessFile(file, "rw");
			for(int i = 0; i < students.length; i++) {
				randomAccessFile.writeChars(students[i].getName());
				randomAccessFile.writeInt(students[i].getScore());
			}
			Scanner scanner = new Scanner(System.in);
			System.out.print("读取第几笔数据?");
			int num = scanner.nextInt();
			randomAccessFile.seek((num-1) * Student.size());
			Student student = new Student();
			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) {
			e.printStackTrace();
		}
	}
	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', ' ');
	}
}

在实例化一个RandomAccessFile对象时,要设定档案开启的方式,设定"r"表示只供读取,设定"rw"表示可读可写;为了让每组数据长度固 定,在写入name时,我们使用 StringBuilder 并设定其长度固定为15个字符,而读回name时则直接读回15个字符,然后再去掉空格符传回。