Eclipse 正在读取一个 Java 字符作为中文

Eclipse is reading a Java char as Chinese

我有两个 类,一个将一系列字符写入文本文件,另一个读取它们。写作部分似乎很好。它有效,我可以打开文件并读取字符,一切看起来都很正常。但是当我尝试读取文件时,它会以“?”的形式输出到控制台。当我调试时,它显示该字符正在被读取为汉字。我将我的编码语言从默认 (Cp 1252) 切换为 UTF-8,这允许控制台读取和显示汉字,但它仍然没有告诉我为什么要解释英文字母 'a'作为'slow'.

的汉字

这是我将字符写入文档的代码:

package iO;

import java.io.*;

public class WriteLetters
{

    public static void main(String[] args) throws IOException
    {
        char[] letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g','h', 'i', 'j', 'k', 'l', 'm', 'n','o', 'p', 'q', 'r', 's', 't', 'u','v', 'w', 'x', 'y', 'z'};
        System.out.println("Opening File...");
        
        
        RandomAccessFile randomFile = new RandomAccessFile("res/Letters.txt", "rw");
        
        System.out.println("Writing to the file...");
        
        for(int i = 0; i < letters.length; i++)
        {
            randomFile.write(letters[i]);
        }
        randomFile.close();
        
        System.out.println("finished writing");
    }

}

这是我读取和打印它们的代码:

    package iO;
    
    import java.io.*;
    
    public class ReadRandomLetters
    {
    
        public static void main(String[] args) throws IOException
        {
            final int CHAR_SIZE = 2;
            long byteNum;
            char ch;
            
            RandomAccessFile raf = new RandomAccessFile("res/Letters.txt","r");
            System.out.println(raf.readChar());
            
            byteNum = CHAR_SIZE * 5;
            raf.seek(byteNum);
            
            ch = raf.readChar();
            
            System.out.println(ch);
    
        }
    
    }

我想我一定是安装了一些语言包或配置错误的设置才会出现这种情况(尽管我也很可能是错的),但我不记得曾为中文做过任何事情。因此,如果有人告诉我如何解决此问题,我将不胜感激。

java.io.RandomAccessFile
public void write(int b) throws java.io.IOException
Writes the specified byte to this file. The write starts at the current file pointer

java.io.RandomAccessFile
public final char readChar() throws java.io.IOException
Reads a character from this file. This method reads two bytes from the file, starting at the current file pointer.

您可能想试试 writeChar。基本上,您当前使用的编码与您正在阅读的编码不同。它试图将两个字节插入为 java 字符,在这种情况下会导致高代码点字符(类似于中文符号)。