2011-09-29 29 views
0

我是mac os的新手。我在java中使用了下面的代碼來獲取系統細節。它打開一個終端來顯示該命令的結果。我需要在文件中獲得這些細節。我怎麼才能得到它。將mac os終端的內容寫入java中的一個文件

String[] command = {"/usr/bin/open", "/Applications/Utilities/System Profiler.app"}; 
Process proc = Runtime.getRuntime().exec(command); 
int resultCode = proc.waitFor(); 
if (resultCode != 0) { 
    throw new Exception("failed to open system profiler"); 
} 

回答

1

通過向用戶打開應用程序,您不能處理任何結果。您需要使用「System Profiler」的命令行版本,該版本將結果打印回shell。 然後,您可以處理結果在Java中,通過使用下面的代碼:

String[] command = {"/usr/sbin/system_profiler"} 
String sendback = "";  
Process proc = Runtime.getRuntime().exec(command); 
InputStream istr = proc.getInputStream(); 
BufferedReader br = new BufferedReader(new InputStreamReader(istr)); 
String str; 
while ((str = br.readLine()) != null) { 
    sendback = sendback + str; 
} 
int resultCode = proc.waitFor(); 
br.close(); 
if (resultCode != 0) { 
    throw new Exception("failed to open system profiler"); 
} 

在Java中,你可以處理結果以任何方式(將其寫入到文件或其他)。

但是,如果你真的想簡單地將其寫入文件(而不是在Java中使用它),你可以做到這一點,通過改變你的命令,並輸出重定向到目標文件上你的shell:

/usr/sbin/system_profiler >/path/to/yourfile.txt