读取.txt文件时,每次输出后缺少一行

时间:2017-08-23 06:28:37

标签: java file bufferedreader bufferedwriter

获取已安装程序的列表后,我将所有程序写入pro.txt文件。

String filename="C:\\Users\\Zeeshan\\Desktop\\pro.txt";
FileWriter fileWriter =new FileWriter(filename);
BufferedWriter br =new BufferedWriter(fileWriter);
String  command = "powershell.exe  \"Get-ItemProperty HKLM:\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* | Select-Object DisplayName | Format-Table –AutoSize\"";
Process p = Runtime.getRuntime().exec(command);
p.getOutputStream().close();
BufferedReader input =new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
int number=0;
while ((input.readLine()) != null)
{
    line=input.readLine();
    br.write(++number+"."+line);
    br.newLine();
}
br.close();
input.close();

但是当我尝试使用缓冲读取器读取该文件时,它总是在每次输出后错过一行。

FileReader fr=new FileReader(filename);
BufferedReader br1=new BufferedReader(fr);
String line1;
while(br1.readLine()!=null)
{
    line1=br1.readLine();
    System.out.println(line1);
}
br1.close();

我的输出就像这种形式。请指导我为什么在最后出现null。

2.                                                             
4.Google Chrome                                                
6.RuntimePack 15.7.22                                          
8.Scan                                                         
10.                                                             
12.                                                             
14.4500K710_Software_Min                                        
16.Apple Software Update                                        
18.Microsoft Visual C++ 2015 x86 Additional Runtime - 14.0.24215
20.WebReg                                                       
22.Update for Microsoft .NET Framework 4.6.1 (KB4014606)        
24.Adobe Refresh Manager                                        
26.Microsoft Visual C++ 2015 x86 Minimum Runtime - 14.0.24215   
28.4500K710                                                     
30.Apple Application Support (32-bit)                           
32.                                                             
34.                                                             
36.BufferChm                                                    
null

2 个答案:

答案 0 :(得分:4)

你在每个循环中读了两行:

while(br1.readLine()!=null)  //first
{
    line1=br1.readLine(); //second
    System.out.println(line1);
}

更改为

while((line1= br1.readLine())!=null)
{
    System.out.println(line1);
}

答案 1 :(得分:1)

创建一个临时布尔变量以继续循环:

EmployeeUnit