以下代码用于在cmd
中运行命令,并使用命令行的输出生成文本文件。下面的代码在Eclipse的输出窗口中显示了正确的信息,但在文本文件中只打印了最后一行。任何人都可以帮我这个吗?
import java.io.*;
public class TextFile {
public static void main(String[] args) throws IOException {
try {
Process p = Runtime.getRuntime().exec("git log");
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
BufferedWriter writer = null;
String line = null;
while ((line = in.readLine()) != null) {
writer = new BufferedWriter(new FileWriter("textfile.txt"));
writer.write(line);
System.out.println(line);
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:2)
正如其他答案中所述,问题是你在循环中创建BufferedWriter
实例,这就是为什么只有最后一行被打印在文件中。
使用try-with-resources
-
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class TextFile {
public static void main(String[] args) throws IOException {
try {
Process p = Runtime.getRuntime().exec("git log");
try (BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter writer = new BufferedWriter(new FileWriter("textfile.txt"))) {
String line = null;
while ((line = in.readLine()) != null) {
writer.write(line);
writer.newLine();
System.out.println(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 1 :(得分:0)
问题是你在循环中创建了一个新的BufferedWriter。其次,您还在循环中关闭编写器。最后,您的代码块有点令人困惑 - 如果您重新格式化代码(在Eclipse中使用Ctrl-F自动执行),代码中的块将更加清晰。
您的代码应如下所示,位于try / catch块的try
部分内:
BufferedWriter writer = (new FileWriter ("textfile.txt"));
String line =null;
while ((line= in.readLine()) !=null) {
writer.write(line);
System.out.println(line);
}
writer.close();