java - 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?
解决方案
您在每次迭代中读取两个字符:一个在while
条件中,一个在循环体中。尝试解决此问题,您的所有代码都会正常工作。
推荐阅读
- excel - 如果单元格值包含特定字符串,则添加到列表框
- notepad++ - 使用 Notepad++ 搜索文件中的多个单词
- google-apps-script - 为什么代码格式损坏并且是错误的,不是很有帮助
- python - 比较两个 3d Numpy 数组并返回带有索引的不匹配值,然后在没有循环的情况下重新创建它们
- python-xarray - 无法将 csv 文件中的 1d 变量添加到 Xarray 数据集 - 错误?
- python - 读取文件时如何处理 UnicodeDecodeError?
- quarkus - 如果调用错误,Quarkus REST 服务返回空响应
- javascript - 将自定义js文件添加到cshtml
- javascript - 提高获取请求加载速度
- postgresql-11 - 在 Azure Database for Postgres 的 PaaS 产品中创建超级用户?