执行java文件并从cmd获取输出

时间:2016-01-29 02:15:35

标签: java

我想编译第二个文件并获取输出,但它会抛出异常。

  public static void main(String[] args) throws IOException, InterruptedException {

    String path="C:\\Users\\Amr\\Documents\\NetBeansProjects\\Second.java";   

    Process pro1 = Runtime.getRuntime().exec("javac " + path);

    ProcessBuilder ps = new ProcessBuilder("java ", path);

    ps.redirectErrorStream(true);

    Process pr = ps.start();

    BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    String line;
    while ((line = in.readLine()) != null) {
        System.out.println(line);
    }
    pr.waitFor();
    System.out.println("ok!");

    in.close();

    pro1.waitFor();

}

从此课程中获取输出

public class Second {
public static void main(String[] args) {
    System.out.println("Hello world from Second.java");
}}

请帮助修复错误

这是错误

Error: Could not find or load main class C:\Users\Amr\Documents\NetBeansProjects\Second.java

1 个答案:

答案 0 :(得分:2)

 ProcessBuilder ps = new ProcessBuilder("java ", path);

您正在执行java Second.java它应该是java Second

替换path.replace(".java","")或创建一个没有" .java"

的变量
nsaravanas@ubuntu:~$ pwd
/home/nsaravanas
nsaravanas@ubuntu:~$ javac com/test/Second.java
nsaravanas@ubuntu:~$ java com.test.Second
Hello world from Second.java
nsaravanas@ubuntu:~$