file.dat 上的字段以这种方式组织:
姓名姓氏姓名姓氏...
我使用这段代码写入文件:
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 值时,它显示中文字符。为什么?