Java启动程序并以编程方式与其进行交互

时间:2018-01-20 05:56:10

标签: java process io

我有一个(Windows)命令行应用程序,启动时会提示您输入密码然后打印一些文本。不幸的是,我不拥有应用程序的源代码,并且应用程序在启动时不会采用任何参数(即,在启动应用程序时无法传递密码)。我需要以编程方式在Java中启动应用程序并向其发送密码,然后阅读响应。虽然我已成功启动其他程序(只有输出),但我似乎无法捕获此应用程序的任何输出。这是我的Java代码:

import java.io.IOException;
import java.io.InputStream;
import java.lang.ProcessBuilder.Redirect;

public class RunCommand {

    public static void main(String[] args) throws Exception {
        new RunCommand().go();
    }

    void go() throws Exception {
        ProcessBuilder pb = new ProcessBuilder("executable.exe");
        pb.redirectErrorStream(true); // tried many combinations of these redirects and none seemed to help
        pb.redirectInput(Redirect.INHERIT);
        pb.redirectOutput(Redirect.INHERIT);
        pb.redirectError(Redirect.INHERIT);
        Process process = pb.start();

        final Thread reader = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final InputStream is = process.getInputStream();
                    int c;
                    while ((c = is.read()) != -1) {
                        // never gets here because c is always = -1
                        System.out.println((char) c);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        reader.start();

        boolean cont = true;
       while (cont) {
           // force this to continue so we can try and get something from the input stream
       }

       process.destroyForcibly();
    }

}

0 个答案:

没有答案