使用Runtime.exec()函数在另一个java程序中执行java程序

时间:2014-03-29 13:32:53

标签: java exec

我给出的以下代码片段是使用exec函数并执行hello程序(简单的“hello world”打印java程序)。但是只要我执行主程序,instream.readline()的print语句就会返回NULL。请尝试解决问题。希望解释清楚。

CODE:

Process process2=null;
BufferedReader inStream=null; 
try
{
    process2 = Runtime.getRuntime().exec("java hello");
}
catch(IOException e1)
{
    System.err.println("Error on exec method");
    e1.printStackTrace();  
}
try
{
    inStream = new BufferedReader(new  InputStreamReader(process2.getInputStream() ));  
    System.out.println(inStream.readLine());
}
catch(IOException e1)
{
    System.err.println("Error on inStream.readLine()");
    e1.printStackTrace();  
} 

2 个答案:

答案 0 :(得分:0)

首先,你的 hello.java 应该已经编译好n 类文件应该出现在程序所在的当前目录中。

为了获得错误,您可以从流程类的对象获取错误流。

BufferedReader stdError = new BufferedReader(new InputStreamReader(pr.getErrorStream()));

String s="";
while ((s = stdError.readLine()) != null) 
System.out.println(s);

答案 1 :(得分:0)

使用Eclipse / java7 / windows

import java.io.BufferedReader;
import java.io.InputStreamReader;


public class ProcessDemo {

    public static void main(String[] args) throws Exception {

        final String dir = System.getProperty("user.dir");
        System.out.println("current dir = " + dir);

        Runtime run = Runtime.getRuntime();
        Process pr=run.exec("javac -d "+ dir +"\\src "+ dir+"\\src\\HelloDemo.java");

        pr.waitFor();

        BufferedReader stdError = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
        BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));

        String line = "";
        String s;

        // read any errors from the attempted command
        System.out.println("Here is the standard error of the command (if any):\n");
                   while ((s = stdError.readLine()) != null) 
                        System.out.println(s);

        //read output
        while ((line=buf.readLine()) != null)
            System.out.println(line);

        pr.destroy();

        Runtime run1 = Runtime.getRuntime();
        Process pr1=run1.exec("java -cp "+dir+"\\src HelloDemo");

        BufferedReader stdError1 = new BufferedReader(new InputStreamReader(pr1.getErrorStream()));
        BufferedReader buf1 = new BufferedReader(new InputStreamReader(pr1.getInputStream()));


        //interpretting file n executing it line by line :D :P

        pr1.waitFor();

        String temp;
        // read any errors from the attempted command
        System.out.println("\n\nHere is the standard error of the command (if any):\n");
                   while ((temp = stdError1.readLine()) != null) 
                        System.out.println(temp);

        //read output
        System.out.println(buf1.readLine());
        while ((temp=buf1.readLine()) != null)
            System.out.println(temp);


    }

}