【问题标题】:run shell command from java从java运行shell命令
【发布时间】:2011-01-28 10:52:03
【问题描述】:

我正在开发一个应用程序,但在从 java 应用程序运行 shell 命令时遇到问题。这是代码:

public String execRuntime(String cmd) {

        Process proc = null;
        int inBuffer, errBuffer;
        int result = 0;
        StringBuffer outputReport = new StringBuffer();
        StringBuffer errorBuffer = new StringBuffer();

        try {
            proc = Runtime.getRuntime().exec(cmd);
        } catch (IOException e) {
            return "";
        }
        try {
            response.status = 1;
            result = proc.waitFor();
        } catch (InterruptedException e) {
            return "";
        }
        if (proc != null && null != proc.getInputStream()) {
            InputStream is = proc.getInputStream();
            InputStream es = proc.getErrorStream();
            OutputStream os = proc.getOutputStream();

            try {
                while ((inBuffer = is.read()) != -1) {
                    outputReport.append((char) inBuffer);
                }

                while ((errBuffer = es.read()) != -1) {
                    errorBuffer.append((char) errBuffer);
                }

            } catch (IOException e) {
                return "";
            }
            try {
                is.close();
                is = null;
                es.close();
                es = null;
                os.close();
                os = null;
            } catch (IOException e) {
                return "";
            }

            proc.destroy();
            proc = null;
        }


        if (errorBuffer.length() > 0) {
            logger
                    .error("could not finish execution because of error(s).");
            logger.error("*** Error : " + errorBuffer.toString());
            return "";
        }


        return outputReport.toString();
    }

但是当我尝试执行命令时:

/export/home/test/myapp -T "some argument"

myapp 将"some argument" 读取为两个单独的参数。但我只想将"some argument" 读取为一个参数。 当我直接从终端运行此命令时,它执行成功。我尝试了'"some argument"'""some argument"""some\ argument",但对我不起作用。我怎么能把这个论点看成一个论点。

【问题讨论】:

    标签: java exec


    【解决方案1】:

    首先创建一个字符串
    String cmd="/export/home/test/myapp -T \"一些参数\"";
    然后在proc中运行cmd

    【讨论】:

    • 除了 Aykut 已经指出的以外,这绝对没有任何作用。
    • @MiladNaseri 除了它正确地转义了 Aykut 实际错误的引号。
    • @Silveri - 除了那不起作用。您不能通过 Java 在命令字符串中使用引号。 Java 不理解 shell 引用。
    【解决方案2】:

    我记得 exec 方法的重载分别为参数提供了一个参数。你需要使用它

    是的。就在这里

    public Process exec(String[] cmdarray)
                 throws IOException
    

    只需让命令行和所有参数分隔字符串数组的元素