简体   繁体   English

Java-RandomAccessFile()格式问题

[英]Java - RandomAccessFile() format issue

My problem is when I get the data from a text file it seems to be in the wrong encoding or somthing. 我的问题是,当我从文本文件中获取数据时,似乎编码或内容错误。 I dont know how to get around this issue sorry. 抱歉,我不知道该如何解决。 Thanks in advance. 提前致谢。 Here is the code. 这是代码。

private static String readLogFile(String path, File f) throws IOException {
    if (f.exists()){
    String data;
        try (RandomAccessFile raf = new RandomAccessFile(f, "rw")) {
            char ch = raf.readChar();
            raf.seek(f.length());
            String dataCh = String.valueOf(ch);
            data = dataCh.toString();
            System.out.println(data);
        }
        return data;
    }

    else{
        String data = "";
        return data;
    }
}

From the Java Docs 从Java文档

This method blocks until the two bytes are read, the end of the stream is detected, or an exception is thrown. 该方法将阻塞,直到读取两个字节,检测到流的末尾或引发异常为止。

Note, "two bytes are read" 注意,“读取两个字节”

Because Java supports Unicode character's the stream is automatically assuming that reading a character from the stream needs to produce a Unicode character. 因为Java支持Unicode字符,所以流自动假定从流中读取字符需要产生Unicode字符。

Try char ch = (char)raf.readByte(); 尝试char ch = (char)raf.readByte(); instead 代替

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM