2011-10-18 32 views
0

在我的java代碼中,我創建了執行某些shell命令的場景,實際上具體執行了-scp--mv-命令。 是否可以記錄執行結果?例如,如果沒有找到要複製的文件,或者-scp--mv-未正確發生,它就會記錄到我準備好的日誌文件中。目前我的命令執行代碼如下:將命令行參數記錄到log4j中

if ("command") { 
       String command = "mv " + source_file_path + "/" 
         + " " + dest_file_path; 
       Process child = Runtime.getRuntime().exec(command); 
       exitVal = child.waitFor(); 

       // Get the input stream and read from it 
       InputStream in = child.getInputStream(); 

       BufferedInputStream bis = new BufferedInputStream(in); 
       ByteArrayOutputStream buf = new ByteArrayOutputStream(); 
       int c = bis.read(); 

       while (c != -1) { 
        byte b = (byte) c; 
        buf.write(b); 
        c = bis.read(); 
       } 
       in.close(); 
       System.out.println("Input Stream: " + buf.toString()); 
       buf.close(); 
       bis.close(); 
       InputStream ein = child.getErrorStream(); 
       BufferedInputStream ebis = new BufferedInputStream(ein); 
       ByteArrayOutputStream ebuf = new ByteArrayOutputStream(); 
       int ce = ebis.read(); 

       while (ce != -1) { 
        // process((char)c); 
        byte be = (byte) ce; 
        ebuf.write(be); 
        ce = ebis.read(); 
       } 
       ein.close(); 
       System.out.println("Error Stream: " + ebuf.toString()); 
       ebuf.close(); 
       ebis.close(); 
     } 
     System.exit(0); 

有無論如何我可以在其上添加一個日誌記錄組件?當文件未找到,文件沒有正確傳輸時,文件傳輸出現問題時記錄。例如

+0

你只是想記錄命令的輸出,或者你想解析命令的輸出並根據情況記錄特定的消息嗎? –

+0

我想根據情況記錄特定的消息。 – user960740

回答

1

解析您在ByteArrayOutputStream中捕獲的命令的輸出,名爲buf,以確定結果並記錄下來。您可能還會從exit code of the process中獲得線索,您將其存儲在exitVal中。

請注意,通過在讀取stdout和stderr流之前調用child.waitFor(),可以保證如果進程的輸出變得太大,這將不起作用。根據Process API docs:「由於某些本地平臺僅爲標準輸入和輸出流提供有限的緩衝區大小,因此無法及時寫入輸入流或讀取子流程的輸出流可能導致子進程阻塞甚至死鎖。」

+0

那麼你有什麼建議?我應該如何處理它? – user960740

+0

你需要更具體。處理什麼? –