【发布时间】:2020-03-12 17:30:48
【问题描述】:
我正在用 Java 编写一个程序来读取 Linux 机器上的 CPU 温度,并每 4 秒将结果输出到一个文件中。 temps 在间隔成功返回到控制台,但不会出现在文件中,也不会引发错误。这也是我第一次使用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);
}
}
【问题讨论】:
标签: java linux text-files bufferedwriter