[英]BufferedWriter isn't writing to file
我正在用 Java 編寫一個程序來讀取 Linux 機器上的 CPU 溫度,並將結果每 4 秒輸出到一個文件。 臨時值按間隔成功返回到控制台,但不會出現在文件中,也不會引發錯誤。 這也是我第一次使用BufferedWriter
,所以如果我使用不當,我深表歉意。
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class tempapp{
public static void main(String[] args) throws IOException, InterruptedException {
String fileName = "temps.txt";
TimerTask task = new TimerTask() {
@Override
public void run(){
// task goes here
List<String> commands = new ArrayList<>();
//build command
commands.add("/usr/bin/sensors");
//args
//commands.add("");
System.out.println(commands);
ProcessBuilder pb = new ProcessBuilder(commands);
pb.directory(new File("/home/ethano"));
pb.redirectErrorStream(true);
Process process = null;
try {
process = pb.start();
} catch (IOException e) {
e.printStackTrace();
}
//Read output
StringBuilder out = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null, previous = null;
while (true) {
try {
if (!((line = br.readLine()) != null)) break;
} catch (IOException e) {
e.printStackTrace();
}
if (!line.equals(previous)) {
previous = line;
out.append(line).append('\n');
System.out.println(line);
try {
File file = new File ("/home/ethano/Desktop/temps.txt");
BufferedWriter wr = new BufferedWriter(new FileWriter(file));
wr.write(line);
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//Check result
try {
if (process.waitFor() == 0) {
//System.exit(0);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
//weird termination
//System.err.println(commands);
//System.err.println(out.toString());
//System.exit(1);
}
};
Timer timer = new Timer();
long delay = 0;
long intervalPeriod = 4 * 1000;
//schedules task to run in interval
timer.scheduleAtFixedRate(task, delay, intervalPeriod);
}
}
您的作者正在將每一行寫入文件。
但是,由於您在每行之前重新打開並截斷文件,並且/usr/bin/sensors
輸出以空行結尾,因此該文件將僅包含最后的最后一個空行。
看到這一點的最簡單方法是告訴您的 FileWriter 追加而不是截斷:
BufferedWriter wr = new BufferedWriter(new FileWriter(file, true));
如果您希望文件包含命令的所有輸出,但僅當它與上次運行不同時,那么顯然您無法逐行進行此確定。 相反,您必須將所有行讀入一個字符串,並將其與上一次運行進行比較。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.