Java 空ProcessBuilder输入流

Java 空ProcessBuilder输入流,java,processbuilder,gnupg,Java,Processbuilder,Gnupg,我在使用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()

我在使用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()时,我总是得到一个NoTouchElementException。 如果我使用gpg命令“-h”,我总是得到预期的输出

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

new ProcessBuilder("cmd", "/c", "C:\\[path]\\GnuPG\\pub\\gpg.exe", "--list-keys");
它有时起作用。但大多数情况下并非如此

为什么??有人能帮忙吗?谢谢

试试这个-

    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);
    }
}
Test Test=新测试();
List命令=new ArrayList();
添加(“C:\[path]\\GnuPG\\pub\\gpg.exe”);
添加(“--list键”);
test.docomand(命令);
}
公共无效doCommand(列表命令)
抛出IOException
{
字符串s=null;
ProcessBuilder pb=新的ProcessBuilder(命令);
Process进程=pb.start();
BufferedReader stdInput=新的BufferedReader(新的InputStreamReader
(process.getInputStream());
BufferedReader stdError=新的BufferedReader(新的InputStreamReader
(process.getErrorStream());
StringBuffer start=新的StringBuffer();
//读取命令的输出
System.out.println(“这是命令的标准输出:\n”);
而((s=stdInput.readLine())!=null)
{
开始。追加;
System.out.println(s.toString());
}
stdInput.close();
//从尝试的命令中读取任何错误
System.out.println(“这是命令的标准错误(如果有):\n”);
而((s=stdError.readLine())!=null)
{
开始。追加;
系统输出打印项次;
}
}

process.getErrorStream()中的任何内容?如果设置
builder.redirectErrorStream(true),是否有帮助?这会将进程的标准错误流重定向到其标准输出流,而无需在单独的线程中读取错误流。错误流中无任何内容。重定向也不起作用。很好的开始,但我只是在“这是命令的标准输出”之后得到一个空行。如果我添加命令行。添加(“cmd”);命令。添加(“/c”);和以前一样。有时我得到回应,有时没有。