2010-09-23 81 views
2

如何使這個工作在Windows上,文件filename.txt沒有被創建。運行時問題

Process p = Runtime.getRuntime().exec("cmd echo name > filename.txt"); 

顯然,期望輸出是一個 「FILENAME.TXT」 應被創建(C:\ Documents和Settings \用戶名\ FILENAME.TXT)與內容 「名稱」。


之所以能夠用下面的代碼來管理,即使該文件是 「FILENAME.TXT」 不被用的ProcessBuilder

 Runtime runtime = Runtime.getRuntime(); 
     Process process = runtime.exec("cmd /c cleartool lsview"); 
     // Directly to file 

//Process p = Runtime.getRuntime().exec( 
//    new String[] { "cmd", "/c", "cleartool lsview > filename.txt" },null, new File("C:/Documents and Settings/username/")); 

     InputStream is = process.getInputStream(); 
     InputStreamReader isr = new InputStreamReader(is); 
     BufferedReader br = new BufferedReader(isr); 
     String line; 

     System.out.printf("Output of running %s is:", 
      Arrays.toString(args)); 

     while ((line = br.readLine()) != null) { 
     System.out.println(line); 
     } 

或使用ProceessBuilder創建,

Process process = new ProcessBuilder("cmd", "/c", "cleartool lsview").start(); 
InputStream is = process.getInputStream(); 
BufferedReader br = new BufferedReader(new InputStreamReader(is)); 

System.out.printf("Output of running %s is:", Arrays.toString(args)); 

String line; 
while ((line = br.readLine()) != null) { 
    System.out.println(line); 
} 
+1

怎麼不工作嗎? – Bozho 2010-09-23 11:06:23

+0

它不起作用的方式? – 2010-09-23 11:06:45

+0

顯然?你是從'C:\ Documents and Settings \ username \'文件夾直接運行它嗎? – 2010-09-23 11:12:33

回答

6

你實際上應使用ProcessBuilder而不是Runtime.exec(請參閱the docs)。

ProcessBuilder pb = new ProcessBuilder("your_command", "arg1", "arg2"); 
pb.directory(new File("C:/Documents and Settings/username/")); 

OutputStream out = new FileOutputStream("filename.txt"); 
InputStream in = pb.start().getInputStream(); 

byte[] buf = new byte[1024]; 
int len; 
while ((len = in.read(buf)) > 0) 
    out.write(buf, 0, len); 

out.close(); 

(我會適應它cmd並呼應,如果我有一個窗口機在到達...隨意編輯這個職位!)

+0

請記住,ProcessBuilder是在JDK 5中引入的。較早版本的JDK仍然需要'Runtime.exec(...)'。 – 2010-09-23 11:14:02

+0

無論您使用ProcessBuilder還是exec(),問題的根源(傳遞在錯誤位置分割的單個字符串)都保持不變。 – musiKk 2010-09-23 11:50:35

+0

我的實際需求是「cmd cleartool lsview> views.txt」,命令cleartool lsview的執行輸出應該轉到views.txt文件。這與正常的cmd提示符正常工作。但在我的java程序中,我喜歡實現這個 – srinannapa 2010-09-23 11:52:03

4

它應該與

Process p = Runtime.getRuntime().exec(
    new String[] { "cmd", "/c", "echo name > filename.txt" }); 

我目前沒有運行Windows,所以很不幸我無法測試它。

背後的原因是,在您的版本中,命令在每個空格字符處被分割。因此,運行時所要做的是創建一個進程cmd併爲其提供參數echo,name,>filename.txt,這是沒有意義的。命令echo name > filename.txtcmd進程的單個參數,因此您必須手動爲不同參數提供一個數組。

如果你想確保該文件是在一個特定的文件夾中創建你必須提供一個工作目錄exec()僅在三個參數版本的工作原理:

Process p = Runtime.getRuntime().exec(
    new String[] { "cmd", "/c", "echo name > filename.txt" }, 
    null, new File("C:/Documents and Settings/username/")); 
+0

平臺相關的解決方案來達到同樣的效果。 – aioobe 2010-09-23 11:09:17

+2

這是一個依賴於平臺的問題:) – Bozho 2010-09-23 11:10:11

+0

是Bozho。我真的不明白這個意見。如果你執行某些事情(幾乎?)總是依賴於平臺。 – musiKk 2010-09-23 11:11:55