我正在尝试通过以下方式写入文件:
for(String s : str){
buffer.put(s.getBytes());
buffer.flip();
channel.write(buffer);
buffer.clear();
}
所以每当我通过char c = (char)randomAccessFile.readChar();
这里我没有得到字符串中的字符。有人可以告诉我原因。
还有一件事为什么转换String
假设尝试字节,即string.getBytes()
,它给出了6个字节。但我们知道char需要2
个字节,所以它应该是16*6=96
。
答案 0 :(得分:0)
RandomAccessFile
期望字节是底层字符串的内存表示。当您调用String.getBytes()
时,您将获得基础字符串的标准表示。以下是与RandomAccessFile
一起使用的示例代码。请注意,它没有使用getBytes()
,而是将基础char
转换为byte
。
public static void main(String [] args) throws IOException {
String str = "foo";
SeekableByteChannel channel = Files.newByteChannel(Paths.get("C:\\tmp\\foo.txt"), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
ByteBuffer buffer = ByteBuffer.allocate(1024);
for(int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
buffer.put((byte)(ch >> 8));
buffer.put((byte)ch);
}
buffer.flip();
channel.write(buffer);
RandomAccessFile file = new RandomAccessFile("/tmp/foo.txt", "rw");
try {
while(true) {
System.out.println(file.readChar());
}
} finally {
file.close();
}
}