1

我正在尝试使用 common-exe 异步方式从 java 程序运行批处理,以便我只能在运行时读取和处理批处理的输出流。

我了解到这段代码异步运行进程

DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
CommandLine cmdLine = new CommandLine("some batch file"); 
Executor executor = new DefaultExecutor(); 
executor.execute(cmdLine, resultHandler);

但现在我的问题是如何从批处理文件中并行读取输出流到执行。我必须处理来自输出流的一些信息。

这是我正在尝试的一段代码..我无法弄清楚如何解决我的问题..

String command = "some batch file.bat";
PipedOutputStream pipedOutputStream = new PipedOutputStream();
PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(pipedOutputStream);
CommandLine commandLine = null;

DefaultExecutor defaultExecutor = new DefaultExecutor();
DataInputStream dataInputStream = null;
DefaultExecuteResultHandler executeResultHandler = new DefaultExecuteResultHandler();

commandLine.parse(command);

try {
    dataInputStream = new DataInputStream(new PipedInputStream(pipedOutputStream));
    defaultExecutor.setStreamHandler(pumpStreamHandler);
    defaultExecutor.execute(commandLine, executeResultHandler);

    InputStream outCmdStream = null;
    pumpStreamHandler.setProcessOutputStream(outCmdStream);
    InputStreamReader outCmdReader = new InputStreamReader(outCmdStream);
    BufferedReader outCmdBufReader = new BufferedReader(outCmdReader);
    String procOutputStr;
    while ((procOutputStr = dataInputStream.readLine()) != null) {
        System.out.println(procOutputStr);
    }
} catch (IOException e) {
    e.printStackTrace();
    System.out.println("ERROR.RUNNING.CMD");
    e.printStackTrace();
    System.out.println("ERROR.RUNNING.CMD");
}
4

2 回答 2

0

我会使用某种委托模式(即某种侦听器或回调,您将在任务中注册)。

当您读入数据时,您将通过约定的方法调用此接口...

while ((procOutputStr = dataInputStream.readLine()) != null) {
    outputHandler.processOutput(procOutputStr);
}

恕我直言

于 2012-10-12T05:06:15.137 回答
0

我在 SwingWorker 抽象类的帮助下实现了这个功能。这个抽象类提供了几个 API 来覆盖,这些 API 可用于在后台执行任务。

以下示例显示了如何使用 swingworker 执行后台线程。

    private Document doc;
 ...
 SwingWorker<Document, Void> worker = new SwingWorker<Document, Void>() {
   @Override
   public Document doInBackground() {
      // any action you want to perform in backgroud
      // i.e. in separate thread
   }
   @Override
   public void done() {
     try {
        // called after background thread is finished
     } catch (InterruptedException ex) {
       ex.printStackTrace();
     } catch (ExecutionException ex) {
       ex.printStackTrace();
     }
   }
 }

以下是文档和教程的链接 http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html http://en.wikipedia.org/wiki/SwingWorker

享受...

于 2013-02-07T04:29:02.317 回答