java - 设置手动编译的类文件的位置

标签 java file-io javac .class-file

我创建了一个类来手动将 .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();
            }
        }

最佳答案

您必须将选项 -d dest_directory 传递给方法 compiler.run(null,null,null,"-d destdirectory",fileToCompile); 请确保目标目录已存在。

来自documentation ,

int run(InputStream in,
        OutputStream out,
        OutputStream err,
        String... arguments)

您可以向该工具传递可变数量的参数。即 javac 工具选项应作为参数传递给此方法

关于java - 设置手动编译的类文件的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21043343/

相关文章:

java - Spring oauth2 自定义 token 问题

java - 如何将数字格式化为标准货币格式(逗号分隔的数字)

java - 多个客户端-Java中的服务器

java - 性能方面,Python VS JAVA 基于文件的处理

java - Java中计算大文件中以字符串开头的行的最快方法是什么

java - 从 ant 更改 javac 路径

Java替换字符串中的一个字符

c++ - 将 ostream 重定向到文件不起作用

java - 在 Annotation Processor for java 中发现方法调用的类

java - 解析javac编译错误