2016-08-17 181 views
1

我想從Java運行Unix查找命令,但它給了我下面的錯誤。 請提出這個正確的方法 -使用Java執行UNIX命令

java命令automation.jar com.amex.scoring.dao.HiveDAO

/bin/sh的:找到/ AXP /輪輞/尼莫的/ dev /日誌 - F型-mtime -5 -exec LS {} \:無此類文件或目錄

Java代碼的

private static final String COMMAND = "find /axp/rim/nemo/dev/logs -type f -mtime -5 -exec ls {} \\;"; 
private static final String SHELL_NAME = "/bin/sh"; 

public static void main(String[] args) throws IOException { 
    final ProcessBuilder pb = new ProcessBuilder(SHELL_NAME,COMMAND); 
    pb.redirectErrorStream(true); 
    final Process process = pb.start(); 
    final BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); 
    String line; 
    while ((line = br.readLine()) != null) { 
     System.out.println(line); 
    } 
} 
+2

添加完整路徑 – Jens

+0

@Jens,抱歉沒有找到你。你想在哪裏添加完整路徑? – RaJ

+0

查找命令,我想也是爲ls命令 – Jens

回答

1

看到它:

package com.raj.shell; 

import java.io.BufferedReader; 
import java.io.InputStreamReader; 

public class ExecuteShellComand { 

    public static void main(String[] args) { 

     ExecuteShellComand obj = new ExecuteShellComand(); 

     String output = obj.executeCommand(); 

     System.out.println(output); 

    } 

    private String executeCommand() { 

     StringBuffer output = new StringBuffer(); 

     try { 

      Process p = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "cd && cat test.txt | grep Hello"}); 
      p.waitFor(); 
      BufferedReader reader 
        = new BufferedReader(new InputStreamReader(p.getInputStream())); 

      String line = ""; 
      while ((line = reader.readLine()) != null) { 
       output.append(line + "\n"); 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return output.toString(); 

    } 

} 
+3

考慮添加一些解釋;指出你的投入爲什麼起作用;而他不是。只是丟棄代碼並沒有很好的答案。 – GhostCat