Home » Java » Why can't I run a Java program from another Java program?

Why can't I run a Java program from another Java program?

Posted by: admin October 21, 2018 Leave a comment

Questions:

I am running the following code. I ask the user to enter a Java program. The user’s program will compile correctly, and if there is any error it will be pointed out. But when I try to run the program it won’t run at all. Instead I get this message:

Program finished with exit code 0.

How do I solve this problem?

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);
        }
}
}
Answers: