0

我在使用 java ProcessBuilder 时遇到了一些问题。我想得到我的 gpg 密钥,所以我使用以下代码:

ProcessBuilder builder = new ProcessBuilder("C:\\[path]\\GnuPG\\pub\\gpg.exe", "--list-keys");
    //builder.directory(new File("C:\\[path]\\GnuPG\\pub\\"));
    Process process = builder.start();

    Scanner s = new Scanner(process.getInputStream()).useDelimiter("\\Z");
    System.out.println(s.next());
    s.close();

但是在执行 s.next() 时,我总是得到 NoSuchElementException。如果我使用 gpg 命令“-h”,我总是得到预期的输出。

如果我将构造函数调用更改为

new ProcessBuilder("cmd", "/c", "C:\\[path]\\GnuPG\\pub\\gpg.exe", "--list-keys");

它有时有效。但大多数时候并没有。

为什么?任何人都可以帮忙吗?谢谢!!

4

1 回答 1

0

尝试这个-

    Test test = new Test();
    List<String> commands = new ArrayList<String>();
    commands.add("C:\\[path]\\GnuPG\\pub\\gpg.exe");
    commands.add("--list-keys");
    test.doCommand(commands);
}


public void doCommand(List<String> command) 
throws IOException
{
    String s = null;

    ProcessBuilder pb = new ProcessBuilder(command);
    Process process = pb.start();

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

    StringBuffer start= new StringBuffer();

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

    // 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)
    {
        start.append(s);
        System.out.println(s);
    }
}
于 2013-10-08T20:22:32.587 回答