java.lang.Runtime异常“无法运行程序” [英] java.lang.Runtime exception "Cannot run program"

查看:536
本文介绍了java.lang.Runtime异常“无法运行程序”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到类似 java.io.IOException的异常:无法运行程序cat / home / talha / * | grep -c TEXT_TO_SEARCH:错误= 2,执行以下命令时没有这样的文件或目录,尽管当我通过终端执行同一命令时没有问题。我需要执行并返回以下命令的输出:

I am getting an exception like java.io.IOException: Cannot run program cat /home/talha/* | grep -c TEXT_TO_SEARCH": error=2, No such file or directory while executing the command below despite that there are no issues when I execute the same command through the terminal. I need to execute and return the output of the command below:

cat /home/talha/* | grep -c TEXT_TO_SEARCH

这里是用于使用 Runtime 类:

public static String executeCommand(String command) {

    StringBuffer output = new StringBuffer();

    Process p;
    try {
        p = Runtime.getRuntime().exec(command);
        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();
}


推荐答案

Runtime.exec不使用一个外壳(例如 / bin / bash );它将命令直接传递到操作系统。这意味着将不会理解通配符,例如 * 和管道( | ),因为 cat (像所有Unix命令一样)不对那些字符进行任何解析。您需要使用类似

Runtime.exec does not use a shell (like, say, /bin/bash); it passes the command directly to the operating system. This means wildcards like * and pipes (|) will not be understood, since cat (like all Unix commands) does not do any parsing of those characters. You need to use something like

p = new ProcessBuilder("bash", "-c", command).start();

或者,如果出于某些奇怪的原因,您需要坚持使用过时的Runtime.exec方法: / p>

or, if for some bizarre reason you need to stick to using the obsolete Runtime.exec methods:

p = Runtime.getRuntime().exec(new String[] { "bash", "-c", command });

如果仅运行cat / grep命令,则应考虑放弃使用外部进程,因为Java代码可以轻松地遍历目录,读取每个文件中的行并将它们与正则表达式匹配:

If you are only running that cat/grep command, you should consider abandoning the use of an external process, since Java code can easily traverse a directory, read lines from each file, and match them against a regular expression:

Pattern pattern = Pattern.compile("TEXT_TO_SEARCH");
Charset charset = Charset.defaultCharset();

long count = 0;

try (DirectoryStream<Path> dir =
    Files.newDirectoryStream(Paths.get("/home/talha"))) {

    for (Path file : dir) {
        count += Files.lines(file, charset).filter(pattern.asPredicate()).count();
    }
}

更新:要递归读取树中的所有文件,使用 Files.walk

Update: To recursively read all files in a tree, use Files.walk:

try (Stream<Path> tree =
    Files.walk(Paths.get("/home/talha")).filter(Files::isReadable)) {

    Iterator<Path> i = tree.iterator();
    while (i.hasNext()) {
        Path file = i.next();
        try (Stream<String> lines = Files.lines(file, charset)) {
            count += lines.filter(pattern.asPredicate()).count();
        }
    };
}

这篇关于java.lang.Runtime异常“无法运行程序”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆