簡體   English   中英

Java ProcessBuilder() 運行一個程序,但該程序不返回任何輸出

[英]Java ProcessBuilder() runs a program, but the program doesn't return any output

我這樣運行程序:

    Process process;
    try {
        process = new ProcessBuilder("java", "-jar", "test.jar", "1", "20").start();
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
          System.out.println(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

我調用的程序使用標准輸出System.out.println("Hello!"); 但是,調用程序一無所獲。 我使用 ProcessBuilder() 錯了嗎? 謝謝!

如果沒有啟動另一個 JVM 的限制(例如:在 test.jar 中使用 System.exit()),您可以在當前 JVM 中加載並運行test.jar

以下片段顯示了原理。

File file = new File("/tmp/test.jar");
URLClassLoader loader = new URLClassLoader(
        new URL[]{file.toURI().toURL()}
);

String className = new JarFile(file)
        .getManifest()
        .getMainAttributes()
        .getValue(Attributes.Name.MAIN_CLASS);

Method main = loader
        .loadClass(className)
        .getDeclaredMethod("main", String[].class);

Object arg = new String[]{"1", "20"};

try {
    main.invoke(null, arg);
} catch (Exception e) {
    // do appropriate exception handling here
    e.printStackTrace(System.err);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM