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

问题描述

尝试将同一程序的 read() 输出打印到控制台上,字符要么丢失,要么杂乱无章。对不同的文件也试过这个,得到同样的问题。

对于相同类型的代码,字节流类和方法 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?

标签: javafilereader

解决方案


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


推荐阅读