[英]How to open/run java program using cmd in another java program
我想通过使用另一个Java程序在cmd中发出Javac命令来编译Java程序,然后运行它。 我怎么做? 有没有我可以使用的课程?
例如,这里是cmd C:\\ Users \\ UserName \\ Documents> Javac HelloWorld.java
我如何在Java程序中编译HelloWorld.java,然后运行它。
这是我的初始源代码,其中有一个目录和一个Java文件。
public class Test {
public static void main(String[] args) {
String directory = "C:\\Users\\UserName\\Documents";
String fileName = "HelloWorld.java";
}
}
尝试这个
try {
// Execute command
String command = "cmd /c start cmd.exe";
Process child = Runtime.getRuntime().exec(command);
// Get output stream to write from it
OutputStream out = child.getOutputStream();
out.write("<execute the java class by mentioning the usual command>");
out.flush();
out.close();
} catch (IOException e) {
}
如果要使用此程序编译其他Java文件,可以尝试此方法。
public class Laj {
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();
System.out.println(command + " exitValue() " + pro.exitValue());
}
public static void main(String[] args) {
try {
runProcess("javac YourDir/HelloWorld.java");
runProcess("java YourDir.HelloWorld");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class HelloWorld {
public static void main(String[] args) {
System.out.println("ok");
}
}
您可能想先编译其他源代码。 Java编译器实际上是用Java本身编写的。 您无需调用javac.exe,而是查看javax.tools.ToolProvider.getSystemJavaCompiler()
ToolProvider Javadoc 。
一旦使用它编译了源代码文件,就可以使用类加载器加载编译器类文件并从那里调用代码,可能是通过反射的方式。
总体而言,您需要高级用例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.