无法使用Runtime.getRuntime()执行来自不同目录的命令.exec(commandArray,null,directory);

时间:2012-09-12 22:00:00

标签: java runtime.exec

我想在openSSL文件夹的bin目录下运行命令。我想从C:\ OpenSSL-Win32 \ bin \目录运行该命令。我需要执行以下命令: Openssl dgst -sha1 -sign PrivateKey.pem -out Record1.sha1 Message.txt

我的代码如下:

import java.io.*;  
public class TestExec {  
    public static void main(String[] args) {  
        try {  
            File directory1 = new File("C:\\OpenSSL-Win32\\bin\\");
            System.out.println(directory1.toString());
            String[] commandArray = {"Openssl dgst -sha1 -sign PrivateKey.pem -out Record1.sha1 Message.txt"};
            Process p2 = Runtime.getRuntime().exec(commandArray, null, directory1);

    } catch (IOException e) {  
        e.printStackTrace();  
    }  
}  
} 

我收到以下IOException:

java.io.IOException: Cannot run program "Openssl dgst -sha1 -sign PrivateKey.pem -out Record1.sha1 Message.txt" (in directory "C:\OpenSSL-Win32\bin"): CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at package1.TestExec.main(TestExec.java:10)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    ... 3 more

请帮我解决这个问题。谢谢。

1 个答案:

答案 0 :(得分:0)

设置工作目录并不意味着java将在该目录中查找可执行文件。它只是设置为可执行文件的当前目录。

我不确定Windows上关于PATH环境变量的确切行为,但是它具有当前设置的内容......

无论如何,我试着改用

String[] commandArray = {"C:\\OpenSSL-Win32\\bin\\Openssl\\Openssl dgst -sha1 -sign PrivateKey.pem -out Record1.sha1 Message.txt"};