3

I want to compile second file and get the output but it throw an Exception .

  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();

}

Get output from this class

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

please any help for repairing the errors

that is the error

Error: Could not find or load main class C:\Users\Amr\Documents\NetBeansProjects\Second.java
7
  • What errors are you getting? And why do you have two main methods? Commented Jan 29, 2016 at 2:18
  • In which class is the first main method located? Still wondering why you have two main methods. Commented Jan 29, 2016 at 2:23
  • It looks like you're attempting to load "Second.java" as a class file. Try replacing Second.java with Second.class Commented Jan 29, 2016 at 2:23
  • @jiaweizhang i want to get output Second class (external class not has a relation with another class ) from cmd Commented Jan 29, 2016 at 2:32
  • @Spencer4134 output the same exception Commented Jan 29, 2016 at 2:33

1 Answer 1

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

You're executing java Second.java it should be java Second

replace path.replace(".java","") or create a variable without ".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:~$
Sign up to request clarification or add additional context in comments.

1 Comment

do your class have package? I've edited my answer,could you check?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.