为什么不能从另一个Java程序运行Java程序?

时间:2018-07-14 09:24:32

标签: java processbuilder

我正在运行以下代码。我要求用户输入Java程序。用户程序将正确编译,如果有任何错误,将指出。但是,当我尝试运行该程序时,它根本不会运行。相反,我收到此消息:

  

程序退出代码为0。

我该如何解决这个问题?

import java.io.*;
import java.util.*;

public class myprog1 {

public static void main(String [] args) throws IOException, InterruptedException {
    System.out.println("enter the candidate name");
    Scanner scan = new Scanner(System.in);
    String cname = scan.next();
    String cfilename = "candidate.java";
    String file1 = "/home/prakasha/IdeaProjects/" + cname;
    String file2 = "/home/prakasha/IdeaProjects/";
    File file = new File("/home/prakasha/IdeaProjects/" + cname);
    file.mkdir();
    if (!file.exists()) {
        System.out.println("filenotfound");
    } else {
        System.out.println("the code is stored in his dir :" + cname);
        File fobj = new File(file, "/" + cfilename);
        FileWriter fw = new FileWriter(fobj);
        System.out.println("enter the code");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String code = br.readLine();
        fw.append(code);
        System.out.println(fobj);
        fw.close();

        ProcessBuilder pb = new ProcessBuilder
                ("javac", file1 + "/" + cfilename);
        pb.inheritIO();

        Process process = pb.start();
        process.waitFor();

        BufferedReader is =
                new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
            // reading the output
        while ((line = is.readLine()) != null)
            System.out.println(line);

        ProcessBuilder pb1 = new ProcessBuilder
                ("java", file1 + "/" + "candidate");
        System.out.println(file1 + "/" + "candidate");
        pb.inheritIO();
        Process process1 = pb1.start();
        BufferedReader reading =
                new BufferedReader(new InputStreamReader(process1.getInputStream()));
        String line1;
        while ((line1 = reading.readLine()) != null)
                System.out.println(line1);
        }
}
}

1 个答案:

答案 0 :(得分:2)

java命令的参数是类名。
/home/prakasha/IdeaProjects/XXX/candidate不是类名,因为/在类名中不是有效字符。

两种解决问题的方法:

  1. 使用-cp参数指定位置。

  2. 将工作目录更改为文件所在的文件夹。

此外,由于您使用inheritIO(),所以没有要复制的输出,因此getInputStream()null input stream

我建议使用第二种解决方法:

new ProcessBuilder("javac", "candidate.java")
        .directory(file)
        .inheritIO()
        .start()
        .waitFor();

new ProcessBuilder("java", "candidate")
        .directory(file)
        .inheritIO()
        .start()
        .waitFor();