3

大きなデータを返す (完了するまでに 2 時間以上かかる) 外部アプリケーションを実行する必要があり、データを継続的に出力します。

私がする必要があるのは、このプログラムを非同期で実行し、出力をファイルにキャプチャすることです。Javaプロセスビルダーを使用してみましたが、プログラムが終了または強制終了された場合にのみハングして出力を返すようです。

プロセスビルダーを使用して、新しいスレッドを作成して出力をキャプチャしようとしましたが、それでも役に立ちませんでした。

次に、apache commons exec について読み、同じことを試しました。ただし、これにも時間がかかるようで、異なるエラーコードを返します(同じ入力に対して)

CommandLine cmdLine = new CommandLine("/opt/testsimulator");

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(stdout);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60*1000);
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(psh);
    executor.setWatchdog(watchdog);
    try {
        executor.execute(cmdLine);
    } catch (ExecuteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

非常に役立つヘルプまたは実際の例

4

1 に答える 1

5

は。を使用ProcessBuilderすると、構成で機能するはずです。たとえば、次のパターンは私にとってはうまくいきます。

ProcessBuilder pb = new ProcessBuilder("/tmp/x");
Process process = pb.start();
final InputStream is = process.getInputStream();
// the background thread watches the output from the process
new Thread(new Runnable() {
    public void run() {
        try {
            BufferedReader reader =
                new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            is.close();
        }
    }
}).start();
// the outer thread waits for the process to finish
process.waitFor();

私が実行しているプログラムは、一連の行を含む単なるスクリプトsleep 1ですecho

#!/bin/sh
sleep 1
echo "Hello"
sleep 1
echo "Hello"
...

Helloプロセスから読み取るスレッドは、毎秒程度吐き出します。

于 2012-05-19T13:06:52.973 に答える