如何使用java中的Process类从第三方命令行程序中获取和获取命令?

时间:2013-06-17 11:20:10

标签: java command-line process command-line-arguments processbuilder

我正在尝试运行一个命令行程序并与之交互,即给出命令以及响应命令,我给出的命令应该改变程序的先前状态。我尝试过并且能够成功执行它但是对于交互部分没有响应。这是我的代码:

 protected void doWork() {
        SwingWorker<String, Void> worker = new SwingWorker<String, Void>() {
            @Override
            protected String doInBackground() throws Exception {
                ProcessBuilder builder = new ProcessBuilder("e:/program files/urjtag/jtag.exe");
                builder.redirectErrorStream(true);
                Process process = builder.start();
                ConsoleReader consoleReader = new ConsoleReader(process.getInputStream());
                consoleReader.start();
                InputStream is = process.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                 String s = "";
                while((s=br.readLine())!=null){
                 System.out.println(s);
                }
                System.out.println(consoleReader.getResult()+" <<<<<<<<<<<<<");
                int waitFor = process.waitFor();
                consoleReader.join();
                switch (waitFor) {
                case 0:
                    return consoleReader.getResult();
                default:
                    throw new RuntimeException("Failed to execute " + builder.command() + " \nReturned message: "
                            + consoleReader.getResult());
                }
            }
            @Override
            protected void done() {
                try {
                    showCommandResult(get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                    showCommandError(e);
                }
            }
        };
        worker.execute();
}

我是从here获得的。

我采用了here中使用BuffuredReader的想法,但该程序没有回复。

此外,当我执行程序时,没有任何显示,但是当我在文件夹中执行它时,它会显示自己的提示。

0 个答案:

没有答案