我是编程新手,我想编译并运行一个外部java文件,如下所示:
import java.util.Scanner;
public class Test{
public static int spr1;
private int spr2;
public static void main(String[]args){
System.out.println("Hello world");
Scanner sc = new Scanner(System.in);
System.out.println(sc.nextInt());
}
}
是否有一种简单的方法(例如使用ProcessBuilder)来运行此程序并从输入中打印一个整数?
编辑:也许我不够清楚:我想在java程序中运行一个EXTERNAL java程序(看起来像那样)。我目前正在制作一个Java编辑器(使用Netbeans),它必须编译并运行一个java程序。我对来自editorWindow的用户输入感到困惑。
编辑2: 我找到了解决方案。这很简单:
ProcessBuilder builderExecute = new ProcessBuilder("java", "Test");
builderExecute.redirectInput(Redirect.INHERIT);
Process p = builderExecute.start();
String line = "";
while ((line = input.readLine()) != null) {
System.out.println(line);
答案 0 :(得分:0)
在另一个Java程序中执行Java程序,我希望这是你要求的。
您可以使用Process和Runtime类来实现此目的。
import java.io.*;
public class TestExec {
public static void main(String[] args) {
try {
Runtime.getRuntime().exec("javac Test.java");
Process p=Runtime.getRuntime().exec("java Test");
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 1 :(得分:0)
阅读此article或this,您也可以阅读帮助(javac -help
)。
<强>更新强>
使用ProcessBuilder
以编程方式编译java文件。
/**
*
* @param path
*/
public static void compile(final String path) {
try {
final Process sqlProcess = getSqlProcess(path);
sqlProcess.waitFor();
if (sqlProcess != null && sqlProcess.exitValue() == 0) {
// Done
System.out.println("Compilation success");
} else {
System.out.println("Compilation fail");
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static Process getSqlProcess(String path) throws Exception {
if (System.getProperty("os.name").toLowerCase().indexOf("linux") >= 0) {
path = path.replaceAll("\\s", "\\\\ ");
String[] executeCmd = new String[]{"/bin/sh", "-c", "javac", path};
return Runtime.getRuntime().exec(executeCmd);
} else {
path = path.replace("\\", "\\\\");
String[] executeCmd = new String[]{"/bin/sh", "-c", "javac", path};
return new ProcessBuilder(executeCmd).start();
}
}