2

Hi guys I want to run java programs inside my javaprogram.

However when I tried to execute java command it tells me this:

java c:\works\Sample stderr: Error: Could not find or load main class c:\works\Sample

This is my code:

private void runButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
        Processor p = new Processor();
        try {
            int k = p.runProcess("javac c:\\works\\Sample.java");
            if (k == 0) {       
                k = p.runProcess("java c:\\works\\Sample");
            }

            System.out.println("Value of k: " + k);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }      

This is my Processor Class

public class Processor {

public void printLines(String name, InputStream ins) throws Exception {
    String line = null;
    BufferedReader in = new BufferedReader(
            new InputStreamReader(ins));
    while ((line = in.readLine()) != null) {
        System.out.println(name + " " + line);
    }
}

public int runProcess(String command) throws Exception {


    Process pro = Runtime.getRuntime().exec(command);
    printLines(command + " stdout:", pro.getInputStream());
    printLines(command + " stderr:", pro.getErrorStream());
    pro.waitFor();
    // System.out.println(command + " exitValue() " + pro.exitValue());
    return pro.exitValue();
}

}

My files were under "C:\works\"

Your responses would be greatly appreciated!

9
  • java is different than javac. One of basic differences it that it expects full.package.name.of.YourClass, not c:/location/of/YourClass. Also it expects in its classpatch parameter location of package with class you want to run. Commented May 31, 2015 at 9:15
  • What If i have no package? Commented May 31, 2015 at 9:16
  • under works folder were the .class file and .java file. Only two files there. Commented May 31, 2015 at 9:17
  • use java -cp locationODirectoryHoldingfYourClassWithoutPackage YourClass Commented May 31, 2015 at 9:17
  • ^that worked! but it writes on my console only. What IF i want it to appear on CMD itself? Commented May 31, 2015 at 9:18

1 Answer 1

1

You can do this by having one master program which you run from your CMD which runs whatever processes you want and redirect input/output of these processes to its own input/output which happens to be your CMD input/output. Here is good example.

Sign up to request clarification or add additional context in comments.

Comments

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.