繁体   English   中英

运行时进程到java中的文件

[英]runtime processes to a file in java

我想得到我的系统的运行进程,即(任务管理器)并将它们保存在一个文件中,但问题是我正在运行进程,但它们没有写入文件我的代码是

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更容易使用,至少在我看来)并且将阅读系统移动到扫描仪中(在我看来也更容易使用)。 我还将Runtime元素移动到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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM