PocessBuilder执行glassfish命令

时间:2016-08-08 06:35:48

标签: java linux cmd terminal glassfish

我尝试获取群集实例列表,因为我使用ProcessBuilder执行命令:

asadmin list-instances --long=true

当我在 windows 中从java执行此命令时,它工作正常,但是当我在Linux中的真实服务器中部署我的应用程序时,我得到一个例外:

  

异常= java.io.IOException:无法运行程序" / bin / sh -c   ' asadmin list-instances --long = true'":error = 2,Aucun fichier ou   档案类型

当我直接在服务器中执行此命令时,它工作正常吗? 我真的无法理解这是什么问题

这是我的Java代码:

public String executerCommande() {
    String line, line2 = "";
    try {
        //Windows command
        //ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", command);
        //I use this with quots and without quotes
        //ProcessBuilder builder = new ProcessBuilder("/bin/sh -c asadmin list-instances --long=true");
        ProcessBuilder builder = new ProcessBuilder("/bin/sh -c 'asadmin list-instances --long=true'");
        builder.redirectErrorStream(true);
        Process p = builder.start();
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while (true) {
            line = r.readLine();
            if (line == null) {
                break;
            }
            line2 += r.readLine() + "\n";
        }
    } catch (Exception e) {
        System.out.println("Exception = " + e);
    }
    return line2;
}

enter image description here

谢谢。

1 个答案:

答案 0 :(得分:1)

使用Runtime可能有帮助

    try {
         String command = "asadmin list-instances --long=true";
         Process p = Runtime.getRuntime().exec(command);
         BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
         for (String s = br.readLine(); s != null; s = br.readLine()) {
                System.out.println("line: " + s);
         }
         br.close();
         p.waitFor();
         System.out.println("command executed exited: " + p.exitValue());
         p.destroy();
    } catch (Exception e) {
        System.out.println("Exception" + e);
    }