FileReader read() 方法打印不正确。除了 int(ASCII rep) 到 char 之外,我还需要做任何额外的转换吗?

FileReader read() method is printing imporperly. Do I need to do any additional conversion besides int(ASCII rep) to char?

尝试将同一程序的 read() 输出打印到控制台,字符丢失或排列混乱。也对不同的文件进行了尝试,遇到了同样的问题。

字节流 class 和方法 FileInputStream.read() 对于相同类型的代码,工作得很好,但这个字符流的结果不同。

import java.io.*;
import java.util.Scanner;
import static java.lang.System.*;

class CSRead1 
{
    public static void main(String[] args) throws IOException
    {
        Scanner input = new Scanner(in);
        out.print("Enter the filename\t>"); 
        String file = input.next();

        try(FileReader fr = new FileReader(file))
        {   while(fr.read() != -1)
            {out.print((char)fr.read());} } //***reading improperly
    }
}

执行时得到:

D:\JavaEx\FILE-IO>java CSRead1
Enter the filename      >CSRead1.java
ipr aaui.cne;
{asCRa1aaln.ytm*
pbi ttcvi anSrn[ rs hosIEcpin
{
        cne nu  e cne(n;
        u.rn(Etrteflnm\>)
        tyFlRae r=nwFlRae(ie)
                hl(rra( =-)
        {u.rn(ca)rra()}}/**edn mrpry

}
?

对于包含唯一字符串的文本文件"Hello"

D:\JavaEx\FILE-IO>java CSRead1
Enter the filename      >sample
el?

您在每次迭代中读取两个字符:一个在 while 条件中,一个在循环体中。尝试解决此问题,您的所有代码都会正常工作。

我曾经在读取其中包含 UTF-8 编码字符的文件时遇到问题。 解决方案是:

String st;
File filedir = new File(filename);
BufferedReader in = new BufferedReader(new InputStreamReader(new 
FileInputStream(filedir), "UTF8"));
while((st = in.readLine()) != null) {
    System.out.println(st); //prints out properly on my side
}

在您的代码中,它看起来像这样:

public static void main(String[] args) throws IOException
{
    Scanner input = new Scanner(in);
    out.print("Enter the filename\t>"); 
    String file = input.next();

    String st;
    File filedir = new File(file );
    BufferedReader in = new BufferedReader(new InputStreamReader(new 
    FileInputStream(filedir), "UTF8"));
    while((st = in.readLine()) != null) {
        System.out.println(st);
    }
}