I want to make a program that open another java programs.how can i run/execute the cmd command in compiling and running java programs.
for example c:\Users\Burnok> javac HelloWorld.java and c:\Users\Burnok> java HelloWorld
how can i do that inside the java program? please help.
I tried this code but it compiled successfully but if i tried to run the HelloWorld.class it says that the could not find or load main class.
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
public class Test {
private static 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);
}
}
private static void runProcess(String command) throws Exception {
Process pro = Runtime.getRuntime().exec(command);
printLines(command + " stdout:", pro.getInputStream());
printLines(command + " stderr:", pro.getErrorStream());
pro.waitFor();
}
public static void main(String[] args) {
try {
runProcess("javac src/HelloWorld.java");
runProcess("java src/HelloWorld");
} catch (Exception e) {
e.printStackTrace();
}
}
}
here is the error java src/HelloWorld stderr: Error: Could not find or load main class src.HelloWorld
-
Check this stackoverflow.com/questions/4842684/…sujithvm– sujithvm2014年08月01日 13:50:59 +00:00Commented Aug 1, 2014 at 13:50
-
i try that but if i tried to run the .class it says that could not find or load main class.user3276091– user32760912014年08月01日 13:53:17 +00:00Commented Aug 1, 2014 at 13:53
-
can you post exactly what you have tried?sujithvm– sujithvm2014年08月01日 13:55:49 +00:00Commented Aug 1, 2014 at 13:55
-
see mkyong.com/java/how-to-execute-shell-command-from-javaLa-comadreja– La-comadreja2014年08月01日 14:02:37 +00:00Commented Aug 1, 2014 at 14:02
-
Have you checked where HelloWorld.class gets generated and where the current context is when you execute? Is is possible the class file is inside the src directory?JustinKSU– JustinKSU2014年08月01日 14:07:22 +00:00Commented Aug 1, 2014 at 14:07
1 Answer 1
Your are supposed to mention class path while running from another directory
syntax is java -classpath directory_to_program Program
try {
runProcess("javac src/HelloWorld.java");
runProcess("java -classpath src HelloWorld");
} catch (Exception e) {
e.printStackTrace();
}
Read for more info How do I run a java program from a different directory?