Warm tip: This article is reproduced from serverfault.com, please click

java-随机存取文件

(java - RandomAccessFile)

发布于 2013-05-15 19:59:52

file.dat上的字段按以下方式组织:

NAME SURNAME NAME SURNAME ...

我使用这一系列代码来写入文件:

RandomAccessFile file = new RandomAccessFile(dir, "rw");

file.seek(file.length());
file.writeChars(setField(this.name.getText()));
file.writeChars(setField(this.surname.getText()));
if (this.kind.equals("teachers")) {
  file.writeChars(setField(this.subject.getText()));
}

file.close();

这是为了阅读:

RandomAccessFile file = new RandomAccessFile(path, "r");

int records = (int)file.length() / 60;

for (int i = 0; i < records; i++) {
    file.seek(file.getFilePointer() + 15);
    if (getContent(file).equals(surname[1])) {
        file.seek(file.getFilePointer() - 15);
        this.name.setText(getContent(file));
        this.surname.setText(getContent(file));
        break;
    }
}

file.close();

getContent()函数:

private String getContent(RandomAccessFile file) throws IOException {
  char content[] = new char[15];

  for (short i = 0; i < 15; i++) {
     content[i] = file.readChar();
  }
  return String.copyValueOf(content).trim();
}

从文件读取并设置JTextField值时,它将显示中文字符。为什么?

Questioner
LppEdd
Viewed
0
Lone nebula 2013-05-16 05:43:49

file.writeChars将每个char字节作为两个字节写入文件。同样,file.readChar从文件中读取两个字节并将其解释为char每当你移动文件指针时,请记住这一点。

例如,如果要跳过15char秒,则必须将文件指针向前移动30个字节,如下所示:file.seek(file.getFilePointer() + 30)看来这就是你做错了。