java - 设置手动编译的类文件的位置
-
21-12-2019 - |
题
我创建了一个类来手动将 .java 文件编译为 .class 文件。该程序运行成功。但是,.class 文件是在与我的 .java 文件相同的目录中创建的。但是,我希望它们在某个自定义目录中创建。我能做些什么?
下面是我用来编译 .java 文件的代码。:-
//***************************//
//这会将我的 .java 文件编译为 .class 文件并将其存储在同一位置
public void compileFile(String pageName,String packageName) {
String fileToCompile = packageName + pageName +".java";
System.out.println("String to compile :- " + fileToCompile );
System.setProperty("java.home", "C:\\install\\Java\\jdk1.7");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int compilationResult = compiler.run(null, null, null, fileToCompile);
if(compilationResult == 0){
System.out.println("Compilation is successful");
}else{
System.out.println("Compilation Failed");
// this.deleteFiles(fileToCompile);
}
}
//此方法尝试将我生成的 .class 文件移动(通过复制和粘贴)到自定义目录中。但它给出了一些错误,例如错误的类文件:mycustomdir MarketWatchBean.Class类文件包含错误的类:mycustomdir.marketwatchbean,请删除或确保其出现在Class Path的正确子目录中。
public void moveFiles(String sourcePath, String destPath){
InputStream inStream = null;
OutputStream outStream = null;
try{
File afile =new File(sourcePath);
File bfile =new File(destPath);
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
//delete the original file
// afile.delete();
System.out.println("File is copied successfully!");
}catch(IOException e){
// this.deleteFiles(sourcePath);
// this.deleteFiles(destPath);
e.printStackTrace();
}
}
解决方案
你必须通过该选项 -d dest_directory
到方法 compiler.run(null,null,null,"-d destdirectory",fileToCompile);
请确保目标目录已存在。
来自 文档,
int run(InputStream in,
OutputStream out,
OutputStream err,
String... arguments)
您可以向该工具传递可变数量的参数。即 javac 工具选项应作为参数传递给此方法
不隶属于 StackOverflow