![](/img/trans.png)
[英]Works in sbt but not raw Java: after using `javac` to compile a .class file, why can't `java` find it?
[英]compile a java class with package name in another java class file by using javac
我正在尝试使用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来编译和运行它们。 但是,如果我在这两个类的前面添加了程序包名称(例如, 程序包compileTest)并将Laj中代码的runProcess部分修改为
runProcess("javac -d . compileTest.simpleTest.java");
runProcess("java compileTest.simpleTest");
该代码将无法正常工作。
谁能帮我,谢谢。
为什么不使用“ JavaCompiler”类来编译Java文件。 请参见下面的示例,我已使用包名称编译了一个Java类。
Package Name = com.main
Class Name = MainClass.java
Source Dir = src
public void compileClass() {
System.setProperty("java.home", "G:\\Java\\Tools\\installed\\JDK"); // Set JDK path it will help to get compiler
File root = new File("/src"); // Source Directory
File sourceFile = new File(root, "com/main/MainClass.java"); // Java file name with package
sourceFile.getParentFile().mkdirs();
try {
new FileWriter(sourceFile).close(); // Read Java file
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
System.out.println(compiler.run(null, null, null, sourceFile.getPath()));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.