문제

Field on file.dat are organized this way:

NAME SURNAME NAME SURNAME ...

I use this piace of code to write to the file:

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();

And this for reading:

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();

The getContent() functions:

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();
}

When reading from the file and setting the JTextField value, it display Chinese characters. Why?

도움이 되었습니까?

해결책

file.writeChars writes each char to the file as two bytes. Similarly, file.readChar reads two bytes from the file and interprets them as a char. Keep this in mind whenever you move the file pointer.

For instance, if you want to skip 15 chars, you'll have to move the file pointer forwards by 30 bytes, like this: file.seek(file.getFilePointer() + 30). It looks like this is what you're doing wrong.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top