从文件中获取不需要的结果

时间:2013-10-21 07:33:14

标签: java encoding io

我正在尝试通过以下方式写入文件:

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

1 个答案:

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