【发布时间】:2014-06-05 01:51:21
【问题描述】:
我正在尝试使用 javac 命令在另一个 java 类文件中编译一个 java 类文件。如果这两个文件没有任何包名就很好了。
上课时间
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
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();
if(pro.exitValue() != 0){
System.out.println(command + " exitValue() " + pro.exitValue());
}
}
public static void main(String[] args) {
try {
runProcess("javac simpleTest.java");
runProcess("java simpleTest");
} catch (Exception e) {
e.printStackTrace();
}
}
}
类 SimpleTest
public class simpleTest {
public static void main(String[] args) {
System.out.println("What's wrong with it");
}
}
我可以使用命令javac Laj.java 和java Laj 很好地编译和运行它们。但是如果我在这两个类的前面加上包名,例如package compileTest,并将Laj中的runProcess部分代码修改为
runProcess("javac -d . compileTest.simpleTest.java");
runProcess("java compileTest.simpleTest");
代码不起作用。
谁能帮帮我,谢谢。
【问题讨论】:
-
我没想到会这样;包是文件夹结构,您的文件不在文件夹结构中。 This question,虽然不是完全重复,但可以让您摆脱最初的痛苦。
-
我认为您需要指定类路径。 IE。使用“-cp”。如果这不起作用,请使用 -cp 参数。