PrintStream 只打印输入文件的最后一行 [英] PrintStream Only Printing out the Last Line of Input File
本文介绍了PrintStream 只打印输入文件的最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个代码
public class program {
public static void main(String[] args) {
try {
String filePath = (args[0]);
String strLine;
BufferedReader br = new BufferedReader(new FileReader(filePath));
//Read File Line By Line and Print the content on the console
while ((strLine = br.readLine()) != null) {
//System.out.println (strLine);
PrintStream out = new PrintStream(new FileOutputStream( //printing output to user specified text file (command line argument: outputfile)
args[1]+".txt"));
out.print(strLine);
}
//close the streams
br.close();
}
catch(IOException e){
System.err.println("An IOException was caught :"+e.getMessage());
}
}
}
如果我使用 java program input.txt 输出从命令行调用这个程序
If I invoke this program from the command line using java program input.txt output
如果输入文件内容是这样的:你好你好再见
and if input file contents were this: hello hi bye
输出文件将打印:再见
它只打印输出的最后一行.
It is only printing the last line of the output.
如果代替:
PrintStream out = new PrintStream(new FileOutputStream( //printing output to user specified text file (command line argument: outputfile)
args[1]+".txt"));
out.print(strLine);
我只有
System.out.println (strLine);
在 while 循环中,它将正确地将输入文件中的每一行打印到控制台.
within the while loop, then it would correctly print each line from the input file to the console.
为什么当我尝试将其打印到另一个文件时,它只打印最后一行?
Why when I try to print it to another file it only prints the last line?
推荐答案
不要在每个循环中创建新的 PrintStream
.而是在 while 循环之前创建 PrintStream
:
Don't create a new PrintStream
in each loop. Instead create the PrintStream
prior to the while loop:
PrintStream out = new PrintStream( ... );
while ((strLine = br.readLine()) != null) {
out.print(strLine);
}
这篇关于PrintStream 只打印输入文件的最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文