【问题标题】:Java exec linux command [duplicate]Java exec linux命令[重复]
【发布时间】:2012-08-23 17:29:37
【问题描述】:

可能重复:
How to make pipes work with Runtime.exec()?

您好,我使用 exec 命令编写了简单的 java 函数。此功能检查系统(linux)中是否存在字体。首先我写了简单的 bash 命令:identify -list font | grep -i 'Font: Times-Bold' -w 并且它的工作完美,所以我创建了简单的程序:

public abstract class SystemReader{

    public static final void checkFontExist(String name){
            String command = "identify -list font | grep -i -w \'Font: "  + name + "\'";
            Process p  =Runtime.getRuntime().exec(command);

            String lines = "";
            String resoults ="";
            BufferedReader bufferedReader = new BufferedReader(new      InputStreamReader(p.getInputStream()));
            while((line  buferedReader.readLine())!=null){
                    resoult += line + "\n";
            }

            System.out.println("RESPONSE: " + resoult);
            bufferreader.close();
    }

}

它的工作,但我不认为。此函数返回我系统中存在的所有字体。 似乎命令 grep 不是 exec ?

我尝试使用我创建的另一个版本的命令 exec():

String command = {"identify -list font", "grep -i -w \'Font: " + fontName + "\'"}

但我有错误:

Exception in thread "main" java.io.IOException: Cannot run program "identify -list font ": java.io.IOException: error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:460)
    at java.lang.Runtime.exec(Runtime.java:593)
    at java.lang.Runtime.exec(Runtime.java:466)

你能给我建议什么是错的吗?非常感谢

【问题讨论】:

  • 管道由 shell 提供,因此您需要手动将一个命令的结果传递给另一个命令。

标签: linux process exec


【解决方案1】:
String[] cmd = {
    "/bin/sh",
    "-c",
    "identify -list font | grep -i -w \'Font: "  + name + "\'"
};

Process p = Runtime.getRuntime().exec(cmd);

将通过 shell 传递命令。这就是你所需要的 | (pipe) 命令由 shell 而不是操作系统提供。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 2013-05-27
    相关资源
    最近更新 更多