我有这个代码
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 程序 input.txt 输出从命令行调用该程序
如果输入文件内容是这样的:
你好
你好
再见
输出文件将打印以下内容:
再见
它只打印输出的最后一行。
如果代替:
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 循环内,它会正确地将输入文件中的每一行打印到控制台。
为什么当我尝试将其打印到另一个文件时,它只打印最后一行?
不要创建新的PrintStream
在每个循环中。相反,创建PrintStream
在 while 循环之前:
PrintStream out = new PrintStream( ... );
while ((strLine = br.readLine()) != null) {
out.print(strLine);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)