java - RandomAccessFile 的意外输出

标签 java randomaccessfile

我正在尝试了解 RandomAccessFile,但在创建测试程序后,我得到了一些奇怪的输出。

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileTest
{
    public static void main(String[] args) throws IOException
    {
        // Create a new blank file
        File file = new File("RandomAccessFileTest.txt");
        file.createNewFile();
        
        // Open the file in read/write mode
        RandomAccessFile randomfile = new RandomAccessFile(file, "rw");
        
        // Write stuff
        randomfile.write("Hello World".getBytes());
        
        // Go to a location
        randomfile.seek(0);
        
        // Get the pointer to that location
        long pointer = randomfile.getFilePointer();
        System.out.println("location: " + pointer);
        
        // Read a char (two bytes?)
        char letter = randomfile.readChar();
        System.out.println("character: " + letter);
        
        randomfile.close();
    }
}

这个程序打印出来

location: 0

character: ?

原来字母的值是“䡥”,而它应该是“H”。

我发现了一个与此类似的问题,显然这是由读取一个字节而不是两个字节引起的,但它没有解释如何准确修复它。

最佳答案

您已使用平台默认编码编写了“Hello World” - 可能每个字符使用一个字节。

您现在正在阅读RandomAccessFile.readChar它总是读取两个字节。文档:

Reads a character from this file. This method reads two bytes from the file, starting at the current file pointer. If the bytes read, in order, are b1 and b2, where 0 <= b1, b2 <= 255, then the result is equal to:

   (char)((b1 << 8) | b2)

This method blocks until the two bytes are read, the end of the stream is detected, or an exception is thrown.

因此,He 被组合成一个字符 - H 是 U+0048,e是 U+0065,因此假设它们已被写入 ASCII 字符,您将读取字节 0x48 和 0x65 并将它们组合成 U+4865这是一个汉字,意思是“移动的车”。

基本上,您不应该使用 readChar 尝试读取此数据。

通常要读取文本文件,您需要一个InputStreamReader(具有适当的编码)包装一个InputStream(例如FileInputStream)。尝试使用 RandomAccessFile 执行此操作并不是很理想 - 您可以将数据读入 byte[],然后将其转换为 >String 但您需要考虑各种微妙之处。

关于java - RandomAccessFile 的意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27972605/

相关文章:

java - 类方法如何访问同一类的另一个实例的私有(private)成员?

java - 现在如何在 JavaFX 中从 TableView 获取 TableHeaderRow?

java - 如何获取JAVA文件中最后写入的位置?

java - 为什么不是 RandomAccessFile.seek(0);将指针移回文件开头?

java - 支持 Long 以外的 RandomAccessFile?

java - 关闭 ZipOutputStream

java - Spring 安全过滤器链模式

java - Java中不同类型的二维数组列表

java - 使用 RandomAccessFile 读取单个 UTF-8 字符

java - 读写性能filechannel和RandomAccessFile谁更好?