【问题标题】:RandomAccessFile - Chinese characters when readingRandomAccessFile - 阅读时的汉字
【发布时间】:2013-05-15 19:59:52
【问题描述】:

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 值时,显示汉字。 为什么?

【问题讨论】:

  • 现在看到我的问题,八年了,我都傻了哈哈哈

标签: java character-encoding character randomaccessfile


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多