Java Runtime.getRuntime():获取执行命令行程序的输出

发布于 2024-11-01 21:03:04 字数 887 浏览 3 评论 0原文

我正在使用运行时从 Java 程序运行命令提示符命令。但是,我不知道如何获取命令返回的输出。

这是我的代码:

Runtime rt = Runtime.getRuntime();

String[] commands = {"system.exe", "-send" , argument};

Process proc = rt.exec(commands);

我尝试执行 System.out.println(proc); 但没有返回任何内容。该命令的执行应返回两个用分号分隔的数字。我怎样才能将其放入变量中以进行打印?

这是我现在使用的代码:

String[] commands = {"system.exe", "-get t"};

Process proc = rt.exec(commands);

InputStream stdIn = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(stdIn);
BufferedReader br = new BufferedReader(isr);

String line = null;
System.out.println("<OUTPUT>");

while ((line = br.readLine()) != null)
     System.out.println(line);

System.out.println("</OUTPUT>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);

但是我没有得到任何输出,但是当我自己运行该命令时,它工作正常。

I'm using the runtime to run command prompt commands from my Java program. However, I'm not aware of how I can get the output the command returns.

Here is my code:

Runtime rt = Runtime.getRuntime();

String[] commands = {"system.exe", "-send" , argument};

Process proc = rt.exec(commands);

I tried doing System.out.println(proc); but that did not return anything. The execution of that command should return two numbers separated by a semicolon. How could I get this in a variable to print out?

Here is the code I'm using now:

String[] commands = {"system.exe", "-get t"};

Process proc = rt.exec(commands);

InputStream stdIn = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(stdIn);
BufferedReader br = new BufferedReader(isr);

String line = null;
System.out.println("<OUTPUT>");

while ((line = br.readLine()) != null)
     System.out.println(line);

System.out.println("</OUTPUT>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);

But I'm not getting anything as my output, but when I run that command myself it works fine.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

∞觅青森が 2024-11-08 21:03:04

方法如下:

Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-get t"};
Process proc = rt.exec(commands);

BufferedReader stdInput = new BufferedReader(new 
     InputStreamReader(proc.getInputStream()));

BufferedReader stdError = new BufferedReader(new 
     InputStreamReader(proc.getErrorStream()));

// Read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
}

// Read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
    System.out.println(s);
}

阅读 Javadoc 了解更多详细信息

Here is the way to go:

Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-get t"};
Process proc = rt.exec(commands);

BufferedReader stdInput = new BufferedReader(new 
     InputStreamReader(proc.getInputStream()));

BufferedReader stdError = new BufferedReader(new 
     InputStreamReader(proc.getErrorStream()));

// Read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
}

// Read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
    System.out.println(s);
}

Read the Javadoc for more details here. ProcessBuilder would be a good choice to use.

¢蛋碎的人ぎ生 2024-11-08 21:03:04

更快的方法是这样的:

public static String execCmd(String cmd) throws java.io.IOException {
    java.util.Scanner s = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

这基本上是这个问题的浓缩版本:

public static String execCmd(String cmd) throws java.io.IOException {
    Process proc = Runtime.getRuntime().exec(cmd);
    java.io.InputStream is = proc.getInputStream();
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    String val = "";
    if (s.hasNext()) {
        val = s.next();
    }
    else {
        val = "";
    }
    return val;
}

我知道这个问题很旧,但我发布这个答案是因为我认为这可能会更快。

编辑(适用于 Java 7 及更高版本)

需要关闭 Streams 和 Scanner。使用 AutoCloseable 来获得简洁的代码:

public static String execCmd(String cmd) {
    String result = null;
    try (InputStream inputStream = Runtime.getRuntime().exec(cmd).getInputStream();
            Scanner s = new Scanner(inputStream).useDelimiter("\\A")) {
        result = s.hasNext() ? s.next() : null;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

A quicker way is this:

public static String execCmd(String cmd) throws java.io.IOException {
    java.util.Scanner s = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

Which is basically a condensed version of this:

public static String execCmd(String cmd) throws java.io.IOException {
    Process proc = Runtime.getRuntime().exec(cmd);
    java.io.InputStream is = proc.getInputStream();
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    String val = "";
    if (s.hasNext()) {
        val = s.next();
    }
    else {
        val = "";
    }
    return val;
}

I know this question is old but I am posting this answer because I think this may be quicker.

Edit (For Java 7 and above)

Need to close Streams and Scanners. Using AutoCloseable for neat code:

public static String execCmd(String cmd) {
    String result = null;
    try (InputStream inputStream = Runtime.getRuntime().exec(cmd).getInputStream();
            Scanner s = new Scanner(inputStream).useDelimiter("\\A")) {
        result = s.hasNext() ? s.next() : null;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}
煞人兵器 2024-11-08 21:03:04

如果类路径上已经有 Apache commons-io 可用,您可以使用:

Process p = new ProcessBuilder("cat", "/etc/something").start();
String stderr = IOUtils.toString(p.getErrorStream(), Charset.defaultCharset());
String stdout = IOUtils.toString(p.getInputStream(), Charset.defaultCharset());

If use are already have Apache commons-io available on the classpath, you may use:

Process p = new ProcessBuilder("cat", "/etc/something").start();
String stderr = IOUtils.toString(p.getErrorStream(), Charset.defaultCharset());
String stdout = IOUtils.toString(p.getInputStream(), Charset.defaultCharset());
素手挽清风 2024-11-08 21:03:04

在撰写本文时,包含代码的所有其他答案都可能导致死锁。

进程的 stdoutstderr 输出缓冲区有限。如果您不同时听它们,那么当您尝试阅读另一个时,其中一个会被填满。例如,当进程等待写入 stderr 时,您可能正在等待从 stdout 读取数据。您无法从 stdout 缓冲区中读取数据,因为它是空的,并且进程无法写入 stderr 缓冲区,因为它已满。你们彼此永远等待着对方。

这是一种读取进程输出而不存在死锁风险的可能方法:

public final class Processes
{
    private static final String NEWLINE = System.getProperty("line.separator");

    /**
     * @param command the command to run
     * @return the output of the command
     * @throws IOException if an I/O error occurs
     */
    public static String run(String... command) throws IOException
    {
        ProcessBuilder pb = new ProcessBuilder(command).redirectErrorStream(true);
        Process process = pb.start();
        StringBuilder result = new StringBuilder(80);
        try (BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())))
        {
            while (true)
            {
                String line = in.readLine();
                if (line == null)
                    break;
                result.append(line).append(NEWLINE);
            }
        }
        return result.toString();
    }

    /**
     * Prevent construction.
     */
    private Processes()
    {
    }
}

关键是使用 ProcessBuilder.redirectErrorStream(true) ,它将把 stderr 重定向到 stderr 。代码>stdout 流。这允许您读取单个流,而无需在 stdoutstderr 之间交替。如果您想手动实现此操作,则必须使用两个不同线程中的流以确保永远不会阻塞。

At the time of this writing, all other answers that include code may result in deadlocks.

Processes have a limited buffer for stdout and stderr output. If you don't listen to them concurrently, one of them will fill up while you are trying reading the other. For example, you could be waiting to read from stdout while the process is waiting to write to stderr. You cannot read from the stdout buffer because it is empty and the process cannot write to the stderr buffer because it is full. You are each waiting on each other forever.

Here is a possible way to read the output of a process without a risk of deadlocks:

public final class Processes
{
    private static final String NEWLINE = System.getProperty("line.separator");

    /**
     * @param command the command to run
     * @return the output of the command
     * @throws IOException if an I/O error occurs
     */
    public static String run(String... command) throws IOException
    {
        ProcessBuilder pb = new ProcessBuilder(command).redirectErrorStream(true);
        Process process = pb.start();
        StringBuilder result = new StringBuilder(80);
        try (BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())))
        {
            while (true)
            {
                String line = in.readLine();
                if (line == null)
                    break;
                result.append(line).append(NEWLINE);
            }
        }
        return result.toString();
    }

    /**
     * Prevent construction.
     */
    private Processes()
    {
    }
}

The key is to use ProcessBuilder.redirectErrorStream(true) which will redirect stderr into the stdout stream. This allows you to read a single stream without having to alternate between stdout and stderr. If you want to implement this manually, you will have to consume the streams in two different threads to make sure you never block.

地狱即天堂 2024-11-08 21:03:04

我们还可以使用流来获取命令输出:

public static void main(String[] args) throws IOException {

        Runtime runtime = Runtime.getRuntime();
        String[] commands  = {"free", "-h"};
        Process process = runtime.exec(commands);

        BufferedReader lineReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        lineReader.lines().forEach(System.out::println);

        BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        errorReader.lines().forEach(System.out::println);
    }

Also we can use streams for obtain command output:

public static void main(String[] args) throws IOException {

        Runtime runtime = Runtime.getRuntime();
        String[] commands  = {"free", "-h"};
        Process process = runtime.exec(commands);

        BufferedReader lineReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        lineReader.lines().forEach(System.out::println);

        BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        errorReader.lines().forEach(System.out::println);
    }
躲猫猫 2024-11-08 21:03:04

@Senthil 和 @Arend 的回答 (https://stackoverflow.com/a/5711150/2268559) 提到了 ProcessBuilder。以下是使用 ProcessBuilder 并指定命令的环境变量和工作文件夹的示例:

    ProcessBuilder pb = new ProcessBuilder("ls", "-a", "-l");

    Map<String, String> env = pb.environment();
    // If you want clean environment, call env.clear() first
    //env.clear();
    env.put("VAR1", "myValue");
    env.remove("OTHERVAR");
    env.put("VAR2", env.get("VAR1") + "suffix");

    File workingFolder = new File("/home/user");
    pb.directory(workingFolder);

    Process proc = pb.start();

    BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));

    BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

    // Read the output from the command:
    System.out.println("Here is the standard output of the command:\n");
    String s = null;
    while ((s = stdInput.readLine()) != null)
        System.out.println(s);

    // Read any errors from the attempted command:
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null)
        System.out.println(s);

@Senthil and @Arend answer (https://stackoverflow.com/a/5711150/2268559) mentioned ProcessBuilder. Here is the example using ProcessBuilder with specifying environment variables and working folder for the command:

    ProcessBuilder pb = new ProcessBuilder("ls", "-a", "-l");

    Map<String, String> env = pb.environment();
    // If you want clean environment, call env.clear() first
    //env.clear();
    env.put("VAR1", "myValue");
    env.remove("OTHERVAR");
    env.put("VAR2", env.get("VAR1") + "suffix");

    File workingFolder = new File("/home/user");
    pb.directory(workingFolder);

    Process proc = pb.start();

    BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));

    BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

    // Read the output from the command:
    System.out.println("Here is the standard output of the command:\n");
    String s = null;
    while ((s = stdInput.readLine()) != null)
        System.out.println(s);

    // Read any errors from the attempted command:
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null)
        System.out.println(s);
伪装你 2024-11-08 21:03:04

如果你用 Kotlin 编写,你可以使用:

val firstProcess = ProcessBuilder("echo","hello world").start()
val firstError = firstProcess.errorStream.readBytes().decodeToString()
val firstResult = firstProcess.inputStream.readBytes().decodeToString()

If you write on Kotlin, you can use:

val firstProcess = ProcessBuilder("echo","hello world").start()
val firstError = firstProcess.errorStream.readBytes().decodeToString()
val firstResult = firstProcess.inputStream.readBytes().decodeToString()
寄居者 2024-11-08 21:03:04

创建类:

public class Utils {
public static final String SHEL_EXECUTE_ERROR = "SHEL_EXECUTE_ERROR";
public static String shellExec(String cmdCommand) {
    final StringBuilder stringBuilder = new StringBuilder();
    try {
        final Process process = Runtime.getRuntime().exec(cmdCommand);
        final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }

    } catch (Exception e) {
        return SHEL_EXECUTE_ERROR;
    }
    return stringBuilder.toString();
}

}

并使用:

final String shellExec = shellExec("cmd /c ver");
final String versionOS = shellExec.equals(SHEL_EXECUTE_ERROR) ? "empty" : shellExec;

Create class :

public class Utils {
public static final String SHEL_EXECUTE_ERROR = "SHEL_EXECUTE_ERROR";
public static String shellExec(String cmdCommand) {
    final StringBuilder stringBuilder = new StringBuilder();
    try {
        final Process process = Runtime.getRuntime().exec(cmdCommand);
        final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }

    } catch (Exception e) {
        return SHEL_EXECUTE_ERROR;
    }
    return stringBuilder.toString();
}

}

and use:

final String shellExec = shellExec("cmd /c ver");
final String versionOS = shellExec.equals(SHEL_EXECUTE_ERROR) ? "empty" : shellExec;
你爱我像她 2024-11-08 21:03:04
Process p = Runtime.getRuntime().exec("ping google.com");

p.getInputStream().transferTo(System.out);

p.getErrorStream().transferTo(System.out);
Process p = Runtime.getRuntime().exec("ping google.com");

p.getInputStream().transferTo(System.out);

p.getErrorStream().transferTo(System.out);
银河中√捞星星 2024-11-08 21:03:04

为了可靠地启动子进程,您需要同时处理输出流,否则当 STDOUT 或 STDERR 填充到默认缓冲区限制时未使用它们时,进程将阻塞。

您可以通过这些测试命令来演示此问题,这些命令以相同的速度将大量数据写入 STDOUT 和 STDERR。如果您的应用程序无法跟上从这两个流的读取,则子进程将冻结/死锁:

// WINDOWS:
String[] commands = {"cmd.exe", "/c", "FOR /L %X IN (1, 1, 10000) DO echo Hello STDOUT %X && echo Hello STDERR %X 1>&2"};
// Linux / Unix style OS
String[] commands = {"/bin/bash", "-c", "for i in {1..10000} ; do echo Hello STDERR $i 1>&2 ; echo Hello STDOUT $i; done"};

您可以通过使用 ProcessBuilder 来避免该问题,它可以更好地控制输出流的去向,并通过调用 pb.redirectErrorStream(true)pb.inheritIO() 或使用 pb.redirectErrorStream(true) 或将 STDOUT / STDERR 重定向到 File 来防止死锁情况code>pb.redirectOutput/Error(file) / 或使用不同的线程从 STDOUT 和 STDERR 读取。

下面是一个简单的示例,说明如何处理启动,它可以用来代替 Runtime.exec() 并将 STDOUT(/STDERR) 发送到您传入的任何流,从而避免死锁情况:

// Example: 
start(command, null, System.out, null);
// or 
start(command, null, System.out, System.err);
// Don't forget to close streams you pass in - if appropriate

public static int start(String[] cmd, byte[] stdin, OutputStream stdout, OutputStream stderr)
        throws IOException, InterruptedException
{
    Objects.requireNonNull(cmd);
    Objects.requireNonNull(stdout);
    System.out.println("start "+Arrays.toString(cmd));

    // Launch and wait:
    ProcessBuilder pb = new ProcessBuilder(cmd);
    if (stderr == null) {
        pb.redirectErrorStream(true);   // No STDERR => merge to STDOUT
    }

    Process p = pb.start();

    // Consumes STDERR at same time as STDOUT, not doing this large streams can block I/O in the sub-process
    Thread bg = null;
    if (stderr != null) {
        Runnable task = () -> {
            try(var from = p.getErrorStream()) {
                from.transferTo(stderr);
            } catch(IOException io) {
                throw new UncheckedIOException(io);
            }
        };
        bg = new Thread(task, "STDERR");
        bg.start();
    }

    // Send STDIN if required, and close STDIN stream
    // NOTE!!! a huge input stream can lock up STDOUT/STDERR readers, you may need a background thread here too
    try(OutputStream os = p.getOutputStream()) {
        if (stdin != null) os.write(stdin);
    }

    // Move STDOUT to the output stream
    try(var stdo = p.getInputStream()) {
        stdo.transferTo(stdout);
    }

    int rc = p.waitFor();
    if (bg != null) {
        bg.join();
    }

    System.out.println("start "+Arrays.toString(cmd));
    System.out.println("Exit "+p.pid()+" CODE "+rc +' '+(rc == 0 ? "OK":"**** ERROR ****")+" "+(stderr == null ? "STDERR>OUT":""));
    return rc;
}

To reliably start a sub-process you need to handle the output streams at same time or the process will block when either STDOUT or STDERR is not consumed when they fill to the default buffer limit.

You can demonstrate this issue by these test commands which write large amount of data to STDOUT and STDERR at same pace. If your app does not keep up with reading from both of these streams then the sub-process will freeze / deadlock:

// WINDOWS:
String[] commands = {"cmd.exe", "/c", "FOR /L %X IN (1, 1, 10000) DO echo Hello STDOUT %X && echo Hello STDERR %X 1>&2"};
// Linux / Unix style OS
String[] commands = {"/bin/bash", "-c", "for i in {1..10000} ; do echo Hello STDERR $i 1>&2 ; echo Hello STDOUT $i; done"};

You can can avoid the problem by using ProcessBuilder which gives better control of where output streams go, and prevent deadlock situation by calling pb.redirectErrorStream(true) or pb.inheritIO() or redirect either of STDOUT / STDERR to File using pb.redirectOutput/Error(file) / or use different threads for reading from STDOUT and STDERR.

Here is a simple example of how to handle launch which could be used in place of Runtime.exec() and sends STDOUT(/STDERR) to any stream you pass in, and which avoids the deadlock situation:

// Example: 
start(command, null, System.out, null);
// or 
start(command, null, System.out, System.err);
// Don't forget to close streams you pass in - if appropriate

public static int start(String[] cmd, byte[] stdin, OutputStream stdout, OutputStream stderr)
        throws IOException, InterruptedException
{
    Objects.requireNonNull(cmd);
    Objects.requireNonNull(stdout);
    System.out.println("start "+Arrays.toString(cmd));

    // Launch and wait:
    ProcessBuilder pb = new ProcessBuilder(cmd);
    if (stderr == null) {
        pb.redirectErrorStream(true);   // No STDERR => merge to STDOUT
    }

    Process p = pb.start();

    // Consumes STDERR at same time as STDOUT, not doing this large streams can block I/O in the sub-process
    Thread bg = null;
    if (stderr != null) {
        Runnable task = () -> {
            try(var from = p.getErrorStream()) {
                from.transferTo(stderr);
            } catch(IOException io) {
                throw new UncheckedIOException(io);
            }
        };
        bg = new Thread(task, "STDERR");
        bg.start();
    }

    // Send STDIN if required, and close STDIN stream
    // NOTE!!! a huge input stream can lock up STDOUT/STDERR readers, you may need a background thread here too
    try(OutputStream os = p.getOutputStream()) {
        if (stdin != null) os.write(stdin);
    }

    // Move STDOUT to the output stream
    try(var stdo = p.getInputStream()) {
        stdo.transferTo(stdout);
    }

    int rc = p.waitFor();
    if (bg != null) {
        bg.join();
    }

    System.out.println("start "+Arrays.toString(cmd));
    System.out.println("Exit "+p.pid()+" CODE "+rc +' '+(rc == 0 ? "OK":"**** ERROR ****")+" "+(stderr == null ? "STDERR>OUT":""));
    return rc;
}
温柔戏命师 2024-11-08 21:03:04

尝试读取运行时的 InputStream

Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-send", argument};
Process proc = rt.exec(commands);
BufferedReader br = new BufferedReader(
    new InputStreamReader(proc.getInputStream()));
String line;
while ((line = br.readLine()) != null)
    System.out.println(line);

如果进程正在打印错误输出,您可能还需要读取错误流 (proc.getErrorStream())。如果使用 ProcessBuilder,则可以将错误流重定向到输入流。

Try reading the InputStream of the runtime:

Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-send", argument};
Process proc = rt.exec(commands);
BufferedReader br = new BufferedReader(
    new InputStreamReader(proc.getInputStream()));
String line;
while ((line = br.readLine()) != null)
    System.out.println(line);

You might also need to read the error stream (proc.getErrorStream()) if the process is printing error output. You can redirect the error stream to the input stream if you use ProcessBuilder.

寄居人 2024-11-08 21:03:04

改编自之前的答案:

public static String execCmdSync(String cmd, CmdExecResult callback) throws java.io.IOException, InterruptedException {
    RLog.i(TAG, "Running command:", cmd);

    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(cmd);

    //String[] commands = {"system.exe", "-get t"};

    BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

    StringBuffer stdOut = new StringBuffer();
    StringBuffer errOut = new StringBuffer();

    // Read the output from the command:
    System.out.println("Here is the standard output of the command:\n");
    String s = null;
    while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
        stdOut.append(s);
    }

    // Read any errors from the attempted command:
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null) {
        System.out.println(s);
        errOut.append(s);
    }

    if (callback == null) {
        return stdInput.toString();
    }

    int exitVal = proc.waitFor();
    callback.onComplete(exitVal == 0, exitVal, errOut.toString(), stdOut.toString(), cmd);

    return stdInput.toString();
}

public interface CmdExecResult{
    void onComplete(boolean success, int exitVal, String error, String output, String originalCmd);
}

Adapted from the previous answer:

public static String execCmdSync(String cmd, CmdExecResult callback) throws java.io.IOException, InterruptedException {
    RLog.i(TAG, "Running command:", cmd);

    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(cmd);

    //String[] commands = {"system.exe", "-get t"};

    BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

    StringBuffer stdOut = new StringBuffer();
    StringBuffer errOut = new StringBuffer();

    // Read the output from the command:
    System.out.println("Here is the standard output of the command:\n");
    String s = null;
    while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
        stdOut.append(s);
    }

    // Read any errors from the attempted command:
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null) {
        System.out.println(s);
        errOut.append(s);
    }

    if (callback == null) {
        return stdInput.toString();
    }

    int exitVal = proc.waitFor();
    callback.onComplete(exitVal == 0, exitVal, errOut.toString(), stdOut.toString(), cmd);

    return stdInput.toString();
}

public interface CmdExecResult{
    void onComplete(boolean success, int exitVal, String error, String output, String originalCmd);
}
丑丑阿 2024-11-08 21:03:04

与此页面上的其他片段几乎相同,但只是通过函数组织内容,我们开始......

String str=shell_exec("ls -l");

类函数:

public String shell_exec(String cmd)
       {
       String o=null;
       try
         {
         Process p=Runtime.getRuntime().exec(cmd);
         BufferedReader b=new BufferedReader(new InputStreamReader(p.getInputStream()));
         String r;
         while((r=b.readLine())!=null)o+=r;
         }catch(Exception e){o="error";}
       return o;
       }

Pretty much the same as other snippets on this page but just organizing things up over an function, here we go...

String str=shell_exec("ls -l");

The Class function:

public String shell_exec(String cmd)
       {
       String o=null;
       try
         {
         Process p=Runtime.getRuntime().exec(cmd);
         BufferedReader b=new BufferedReader(new InputStreamReader(p.getInputStream()));
         String r;
         while((r=b.readLine())!=null)o+=r;
         }catch(Exception e){o="error";}
       return o;
       }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文