char[] input =new char[24];
for (int i=0; i<24; i++){
input[i] = (char)('a'+i);
}
RandomAccessFile bf = new RandomAccessFile("data1.txt", "rw");
for(int i=0; i<24; i++){
bf.writeChar(input[i]);
}
使用上面的代码,当我打开文件时,它似乎是“abcd...”,正如我所料,但是当我尝试读取文件时
RandomAccessFile rf1 = new RandomAccessFile("data1.txt", "r");
rf1.seek(0);
System.out.println(rf1.readChar());
rf1.seek(1);
System.out.println(rf1.readChar());
rf1.close();
它按预期给出了“a”,但是当seek(1)时它给了我?而不是 b,为什么?
最佳答案
一个char是16位,即2个字节。您正在从第一个字符的中间读取,这会导致无法映射的 unicode 字符(被翻译为“?”)。您想要执行seek(2)
。
来自 public final void writeChar(int v)
的 javadoc:
Writes a char to the file as a two-byte value, high byte first. The write starts at the current position of the file pointer.
关于java - 用RandomAccessFile写入和读取的格式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22972023/