2016-04-06 33 views
1

我想要得到我的系統正在運行的進程(即任務管理器)並將它們保存在一個文件中,但問題是我正在運行進程但它們沒有寫入文件 我的代碼是運行時進程到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(); 
+1

如果您只是寫入System.out,會得到什麼輸出結果? –

+0

圖像名稱PID會話名稱會話編號使用 系統空閒進程0服務0 24 K 系統4服務0 304 K @ScaryWombat –

+0

看不到此代碼的任何問題。任何未報告的錯誤? –

回答

0

試試這個。我把它移到了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();