我已经创建了一个类来手动将我的.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请删除或者确保它出现在类路径的正确子目录中。
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();
}
}发布于 2014-01-10 11:44:49
您必须将选项-d dest_directory传递给compiler.run(null,null,null,"-d destdirectory",fileToCompile);方法,请确保目标目录已经存在。
从文档,
int run(InputStream in,
OutputStream out,
OutputStream err,
String... arguments)可以将可变数量的参数传递给该工具。应该将javac工具选项作为该方法的参数传递。
https://stackoverflow.com/questions/21043343
复制相似问题