我想获取系统的正在运行的进程,即(任务管理器)并将它们保存在文件中,但问题是我正在获取正在运行的进程,但它们没有写入文件 我的代码是
BufferedWriter out = new BufferedWriter(new FileWriter("C:\\Users\\Zeeshan Nisar\\Desktop\\process.txt", true));
// Get process and make reader from that process
Process p = Runtime.getRuntime().exec("tasklist.exe");
BufferedReader s = new BufferedReader(new InputStreamReader(p.getInputStream()));
// While reading, print.
String input = null;
while ((input = s.readLine()) != null) {
out.write(input);
out.newLine();
}
out.close();
最佳答案
试试这个。我将其移至 PrintWriter(主要是因为它比 BufferedWriter 更易于使用,至少在我看来),并将阅读系统移至 Scanner(在我看来,也是因为它更易于使用)。我还将运行时元素移动到 ProcessBuilder 中,并将错误流重定向到标准输出。
// Make a PrintWriter to write the file
PrintWriter printer = new PrintWriter("process.txt");
// Make a process builder so that we can execute the file effectively
ProcessBuilder procBuilder = new ProcessBuilder();
procBuilder.command(new String[] { "your", "commands" }); // Set the execution target of the PB
procBuilder.redirectErrorStream(true); // Make it slam the error data into the standard out data
Process p = procBuilder.start(); // Start
// Scan the process
Scanner scan = new Scanner(p.getInputStream());
while (scan.hasNextLine()) {
printer.println(scan.nextLine()); // While it provides data, print to file
}
// Close everything to prevent leaks
scan.close();
printer.close();
关于java - java 中的运行时进程处理文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36441607/