2013-08-19 50 views
4

我嘗試了一個簡單的程序在運行時執行Linux命令。但是下面的程序會被編譯並且運行時沒有任何錯誤,但是文本文件並沒有像預期的那樣被創建。這個程序有什麼問題嗎?Java - 運行時命令執行

import java.io.*; 
class ExecuteJava 
{ 
    public static void main(String args[]) 
    { 
      String historycmd = "cat ~/.bash_history >> Documents/history.txt"; 
      try 
      { 
        Runtime runtime = Runtime.getRuntime(); 
        Process proc = runtime.exec(historycmd); 
      } 
      catch(Exception e) 
      { 
        System.out.println(e); 
      } 
    } 
} 
+2

此代碼正嘗試寫入progam正在運行的當前目錄中名爲'Documents'的目錄。該目錄是否存在? – andy256

+0

@ andy256是的,它的確如此。 –

回答

1

附加運算符>>意味着被解釋爲命令shell的一部分。使用

String[] historycmd = 
      { "bash", "-c", "cat ~/.bash_history >> Documents/history.txt"}; 
+0

謝謝:)這個效果很好。 –

2

嘗試訪問Process提供的一些功能。我會從exitValue開始。通常情況下,-1表示出現了問題,而0意味着沒有發生特別糟糕的事情。

也試試InputStreamError Stream,並完整閱讀。看看是否有任何有用的反饋。

除此之外,請嘗試和y256在評論中建議的內容。確保Documents目錄存在於程序的執行目錄中。