如何从Java代码内部执行shell脚本输出?

时间:2014-10-22 15:26:42

标签: java shell inputstream outputstream processbuilder

我需要从Java执行以下脚本,并能够在控制台上查看结果。但是在控制台上看不到echo语句。在网上花了一些时间后,我能够理解我需要控制输入输出流才能做到这一点。但我没有获得使这成为可能的信息。

我已经发布了以下脚本和Java语句:

脚本:

#!/bin/sh
echo "Hello World"
echo "$1 $2"
exit 0

Java代码:

List<String> command = new ArrayList<String>();
command.add("sh");
command.add("sript.sh");
command.add("Technopath007");
command.add("Dennis");
ProcessBuilder builder = new ProcessBuilder(command);
Process process = builder.start();
BufferedReader is = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = is.readLine()) != null)
    System.out.println(line);       

该主题的现有主题似乎不起作用。

请让我知道我在这里缺少什么。提前致谢。

2 个答案:

答案 0 :(得分:0)

使用BufferedReader

这样的事情:

BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
string line = "";
while ((line = reader.readLine()) != null)
    System.out.println(line);
reader.Close();

答案 1 :(得分:-1)

试试这个:

/** Execute a command where each parameter is in the string array. It is better to
 * do such a call this way because passing a single string to the java
 * Runtime.getRuntime().exec("single long string") method invokes StringTokenizer
 * to split the string into an array of strings and it does a poor job at it.
 *
 * I.e. The string:
 *    ksh -c "mkdir /tmp/test"
 *
 * is split thus:
 *
 *    ksh
 *    -c
 *    "mkdir
 *    /tmp/test"
 *
 * and then the shell interpreter complains about unmatched quotes.
 *
 * Returns a list which is whatever was put
 * on the stdout, followed by what was put on stderr.
 * @param exec the execution array, the first entry is the executable to run.
 * Don't forget that shell builtin command must be run within a shell.
 * @return The output list.
 */
public List executeExactCommand(String exec[])
{
    int exitCode   = 3;  // Assume we failed
    List execOutput = new ArrayList();

    String execCmd = "";
    int    i;

    for (i = 0; i < exec.length; ++i) {
        execCmd += (((i != 0) ? " " : "") + exec[i]);
    }

    try {
        Process p = Runtime.getRuntime().exec(exec);

        try {
            InputStream  is   = p.getInputStream();
            StringBuffer desc;
            int          chr = 0;

            while (chr >= 0) {
                desc = new StringBuffer(5192);
                chr  = is.read();

                for (i = 0; (i < 5192) && (chr >= 0) && (chr != '\n'); chr = is.read()) {
                    // Because of Bill Gates, everyone in the world has to
                    // process for a possible, useless, RETURN character.
                    if (chr != '\r') {
                        desc.append((char) chr);
                        ++i;
                    }
                }

                if ((chr >= 0) || (desc.length() != 0)) {
                    execOutput.add(desc.toString());
                }
            }

            is  = p.getErrorStream();
            chr = 0;

            while (chr >= 0) {
                desc = new StringBuffer(5192);
                chr  = is.read();

                for (i = 0; (i < 5192) && (chr >= 0) && (chr != '\n'); chr = is.read()) {
                    // Because of Bill Gates, everyone in the world has to
                    // process for a possible, useless, RETURN character.
                    if (chr != '\r') {
                        desc.append((char) chr);
                        ++i;
                    }
                }

                if ((chr >= 0) || (desc.length() != 0)) {
                    execOutput.add(desc.toString());
                }
            }

            exitCode = p.waitFor();

            if (withCommandTrace) {
                execOutput.add("execCmd = " + execCmd + " (" + exitCode + ")");
            }
        }
        catch (InterruptedException x) {
            System.err.println("Error command interupted, cmd='" + execCmd + "'");
            System.err.println("Caught: " + x);
            execOutput.add("Error command interupted, cmd='" + execCmd + "'");
            execOutput.add("" + exitCode);
        }
    }
    catch (IOException x) {
        // couldn't exec command
        System.err.println("Error executing command, command=" + execCmd);
        System.err.println("Caught: " + x);
        execOutput.add("Error executing command, cmd='" + execCmd + "'");
        execOutput.add("" + exitCode);
    }

    if (withCommandTrace) {
        for (i = 0; (execOutput != null) && (i < execOutput.size()); ++i) {
            System.out.println((String) execOutput.get(i));
        }
    }

    return execOutput;
}

您可以使用以下内容来调用它:

List eachOutputLines = executeExactCommand(["bash", "-c", "ls -la /"]);