Java exec linux命令

时间:2012-08-23 17:29:38

标签: linux process exec

  

可能重复:
  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)

你能告诉我什么是错的吗?非常感谢

1 个答案:

答案 0 :(得分:6)

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

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

将通过shell传递命令。这是你需要的,因为| (管道)命令由shell而不是操作系统提供。