1

我有一个hello world类 hworld.class 在控制台上显示“Hello World”。我正在尝试使用代码从控制台中的另一个类运行它

 public class ftest2  
 {  
    public static void main(String[] arg)  
    {  
     System.out.println("NEW FILE PRINT LINE EXECUTED");
      try {  
            Process pro1 = Runtime.getRuntime().exec("javac hworld.java");  
            pro1.waitFor();  
            Process pro2 = Runtime.getRuntime().exec("java hworld");  
            pro2.waitFor();  
         } catch (Exception e) {    
               System.out.println("Some Error");   
               e.printStackTrace();     
                }  
    }  }   

但是当文件被执行时,Hello World 的输出并没有显示在控制台上。
程序刚刚启动并显示

  NEW FILE PRINT LINE EXECUTED    

安装的

  NEW FILE PRINT LINE EXECUTED    
  HELLO WORLD    

如何也可以显示 HELLO WORLD 的输出。
(这是示例程序。我想在另一个程序中显示一个程序的输出)

如果有另一种方法可以在另一个类中调用一个类来显示其输出。那么请提一下。

4

3 回答 3

5

您需要阅读InputStream该过程的内容,即

流从这个 Process 对象表示的进程的标准输出流中获取数据。

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

读取InputStream和写入System.out

    InputStream inputStream = process.getInputStream();
    int b = -1;
    while ( (b =  inputStream.read()) != -1 ) {
        System.out.write(b);
    }
于 2012-12-30T13:47:41.440 回答
1

您需要将进程的输入流重定向到 System.out,例如:

public static void main(String[] arg) {
    System.out.println("NEW FILE PRINT LINE EXECUTED");
    try {
        Process pro1 = Runtime.getRuntime().exec("javac hworld.java");
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(pro1.getInputStream(), Charset.forName("UTF-8")))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

注意:它使用 Java 7 的 try with resources 语法,但如有必要,可以轻松转换为 Java 6。

于 2012-12-30T13:48:43.630 回答
0

可能是您遇到异常并且您没有打印它。

public class ftest2  
 {  
    public static void main(String[] arg)  
    {  
     System.out.println("NEW FILE PRINT LINE EXECUTED");
      try {  
            Process pro1 = Runtime.getRuntime().exec("javac hworld.java");  
            pro1.waitFor();  
            Process pro2 = Runtime.getRuntime().exec("java hworld");  
            pro2.waitFor();  
         } catch (Exception e) {
            System.out.println("Some Error");
            e.printStackTrace(); 
         }  
    }  
} 

和另一种方式

public static void main(String[] arg)  
{  
     System.out.println("NEW FILE PRINT LINE EXECUTED");
     hworld.main(arg); // since main is a static method can be called w/o instance
}
于 2012-12-30T13:40:23.620 回答