Trying to execute a Java jar with Runtime.getRuntime().exec()

前端 未结 1 1427
轻奢々
轻奢々 2020-12-20 03:21

In the project I am working on, I need to execute a script that I have in a resources folder -- in the class path. I am simply testing the final script functionality, since

相关标签:
1条回答
  • 2020-12-20 03:39

    Use the Process instance returned by exec()

    Process cat = Runtime.getRuntime().exec("java -jar C:/cat.jar C:/test.txt");
    BufferedInputStream catOutput= new BufferedInputStream(cat.getInputStream());
    int read = 0;
    byte[] output = new byte[1024];
    while ((read = catOutput.read(output)) != -1) {
        System.out.println(output[read]);
    }
    


    References:
    http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html

    By default, the created subprocess does not have its own terminal or console. All its standard I/O (stdin, stdout, stderr) operations will be redirected to the parent process, where they can be accessed via the streams obtained using the methods getOutputStream(), getInputStream(), and getErrorStream().

    http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html#getInputStream()

    getInputStream() returns the input stream connected to the normal output of the subprocess.

    0 讨论(0)
提交回复
热议问题