为什么Java缓冲读取器错过输出大文本文件中的很多行作为输入?
问题描述:
我喜用下面的代码为什么Java缓冲读取器错过输出大文本文件中的很多行作为输入?
public class Readfiles {
FileInputStream fr;
public void readAll(){
try {
fr = new FileInputStream(new File("books/Artificial intelligence.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("File Not Found");
e.printStackTrace();
}
CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
decoder.onMalformedInput(CodingErrorAction.IGNORE);
InputStreamReader reader = new InputStreamReader(fr, decoder);
BufferedReader br = new BufferedReader(reader);
try {
int i = 0;
for(String newLine; (newLine = br.readLine()) != null;)
{
newLine = br.readLine();
i++;
System.out.println(newLine);
}
br.close();
System.out.println(i);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
要读这个txt文件是约420.000线长: Artificial intelligence.txt
但我上面的代码不读它正确地是缺少有关一半在中间,并且似乎从任何地方开始(每次随机开始)以下是SYSOut的可能结果之一:
只有第一行:
#@Margaret H. Szymanski,Paul M. Aoki,Rebecca E. Grinter,Amy Hurst,James D. Thornton,Allison Woodruff
#cComputer Supported Cooperative Work
#%5488
#%87739
#%257074
#%818174
#!
#*Unpacking Tasks: The Fusion of New Technology with Instructional Work.
#t2008
#index831790
#%174882
#!
所以问题是为什么?
我的打印输出总是209647.
答
那么你正在阅读的线
for(String newLine; (newLine = br.readLine()) != null;)
{
两次
一次,然后又在
newLine = br.readLine();
更好会是
while ((newLine = br.readLine()) != null) {....}
答
您在循环中呼叫br.readLine()
两次,但仅在您的System.out.println
呼叫中使用这两个呼叫中的一个呼叫的结果。所以你只打印出每一行。
+0
哦,你是如此愚蠢的失败,谢谢它是固定的! –
答
你打电话br.readLine()
两次
for(String newLine; (newLine = br.readLine()) != null;)
{
newLine = br.readLine();
i++;
System.out.println(newLine);
}
你可以摆脱一个的循环
for(String newLine; (newLine = br.readLine()) != null;)
{
i++;
System.out.println(newLine);
}
答
for(String newLine; (newLine = br.readLine()) != null;)
{
i++;
System.out.println(newLine);
}
哦,你是如此的右边是愚蠢的失败里面,由于它是固定的! –