如何在另一个java程序中运行java可执行jar

时间:2013-03-29 09:50:22

标签: java

我知道之前已经问过这个问题,但这些答案没有给我答案。

我想在我的java程序中执行exec jar文件,并将执行jar的输出变为字符串。下面是我到目前为止使用的代码没有成功。

cmdlink = "java -jar iwtest-mac.jar"+" "+cmd;
            System.out.println(cmdlink);
             Process process = Runtime.getRuntime().exec(cmdlink);
             BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
             while ((reader.readLine()) != null) {
                 st = reader.readLine();  

             }
             process.waitFor();

我尝试过的另一个代码如下:

String cmdlink = "iwtest-mac.jar "+cmd;    
          ProcessBuilder pb = new ProcessBuilder("java", "-jar", cmdlink); //cmd here is a string that contains inline arguments for jar.
            pb.redirectErrorStream(true);
            pb.directory(new File("C:\\Users\\Dharma"));

            System.out.println("Directory: " + pb.directory().getAbsolutePath());
            Process p = pb.start();
            InputStream is = p.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            for (String line = br.readLine(); line != null; line = br.readLine()) {
                    System.out.println( line ); 
            p.waitFor();

以上两点都不适合我。任何建议都表示赞赏。

1 个答案:

答案 0 :(得分:12)

这对我有用..

public class JarRunner {
    public static void main(String[] args) {
        ProcessBuilder pb = new ProcessBuilder("java", "-jar", "C:\\JCcc.jar");
        pb.directory(new File("C:\\"));
        try {
            Process p = pb.start();
            LogStreamReader lsr = new LogStreamReader(p.getInputStream());
            Thread thread = new Thread(lsr, "LogStreamReader");
            thread.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class LogStreamReader implements Runnable {

    private BufferedReader reader;

    public LogStreamReader(InputStream is) {
        this.reader = new BufferedReader(new InputStreamReader(is));
    }

    public void run() {
        try {
            String line = reader.readLine();
            while (line != null) {
                System.out.println(line);
                line = reader.readLine();
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这是Docs所说的 -

ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");

您可以在构造函数中传递任意数量的参数。

详细了解流程构建器here