2017-02-12 65 views
1

我試圖執行命令行來複制文件夾,但沒有任何反應。我從命令行嘗試了相同的命令,它工作正常。 代碼試圖在Java中使用xcopy來複制文件夾

Runtime rt = Runtime.getRuntime(); 
    String line; 
    try { 

     Process pr = rt.exec("xcopy //E //I notts nots2"); 

     InputStreamReader mInputStreamReader = new InputStreamReader(pr.getInputStream()); 
     BufferedReader input = new BufferedReader(mInputStreamReader); 

      while ((line = input.readLine()) != null) 
       System.out.println(line); 
    } catch (IOException e) { 
    ted=ted+1; 
    } 
+1

你能告訴我們什麼被放入錯誤流嗎? –

+0

另外,你應該做一些IOException。代碼寫入的方式是反模式。看[隱藏錯誤](https://en.wikipedia.org/wiki/Error_hiding)。順便說一句......誰是'ted'? –

回答

1

1)pr.getInputStream()是不夠的,因爲它不會讀取處理執行過程中遇到的錯誤輸出。
您還應該閱讀錯誤流:pr.getErrorStream()

2)您應該指定進程的工作目錄,否則進程將繼承當前進程的工作目錄。

例如:

Process pr = rt.exec("xcopy //E //I notts nots2", null, new File("yourWorkingDirToRunTheProcess")); 
0

看答案this question。它解釋瞭如何使用該過程的標準輸出和標準錯誤流。

您還應該考慮使用java API方法複製文件,而不是運行外部進程。一個原因是你的命令(xcopy)不能在Windows以外的任何地方工作。另一個原因是運行外部進程比使用標準API方法更容易出錯。