1

I have 2 classes one is a simple one

Sample.java

public class Sample {
  public static void main(String args[]) {

    System.out.println("Hello World!!!!!");
  }
}

Other one is something like this

Main.java

public class Main
{  
  public static void main(String[] args) throws Exception
  {
     Runtime.getRuntime().exec("java Sample");
  }
}

I am basically trying to run the Main.java program to call Sample.java in a new command prompt...that is a new cmd that should open and print the output of Sample.java...how should I do this...???

davide
  • 1,918
  • 2
  • 20
  • 30
Rahul Mehrotra
  • 639
  • 5
  • 15
  • 31

4 Answers4

4

Compile the two together, and then from Sample,

Main.main(args);

will do the trick. You don't need to import since you're in the same package. Note the linked tutorial. http://docs.oracle.com/javase/tutorial/java/package/index.html

Siddh
  • 712
  • 4
  • 21
2
Runtime.getRuntime().exec("cmd /c start cmd.exe /K \"cd <where_the_Sample_is> && javac Sample.java && java Sample\"");

or if the class is already compiled:

Runtime.getRuntime().exec("cmd /c start cmd.exe /K \"cd <where_the_Sample_is> && java Sample\"");
jlordo
  • 37,490
  • 6
  • 58
  • 83
stan
  • 984
  • 10
  • 15
2

I am using eclipse. The class files are placed in the bin directory located under the projects directory. The below code starts command prompt, changes directory to bin and issues java Sample command. You can edit it up to your requirement.

Runtime.getRuntime().exec("cmd.exe /c cd \"bin\" & start cmd.exe /k \"java Sample\"");

Macrosoft-Dev
  • 2,195
  • 1
  • 12
  • 15
0

You can use this code:

public class Main {
    public static void main(String[] args) throws Exception {
        Class<Sample> clazz = Sample.class;
        Method mainMethod = clazz.getMethod("main", String[].class);
        String[] params = null;
        mainMethod.invoke(null, (Object) params);
    }
}
Manitra
  • 111
  • 5