JavaCompiler 编译JAVA文件并指定输出路径

新手勿喷!!

前几年有个很牛的同事自己写了个java的编译插件,要比ant快很多。今天自己尝试着写了一个,使用的还是javatool里的JavaCompiler进行编译操作,虽然并没有什么乱用,不想再做深入的研究,但可以给想自己写编译的人提供一下参考。

大体说一下,代码里是使用JavaFileManager去加载需要编译的java文件,编译操作时给ComplitionTask指定javac执行的参数option,使用JavaFileManager也可以指定一些参数,不过不推荐,毕竟option是针对操作不是针对文件。option是个Iterator类型,开始我加入的是这样的:"-d d:",但是一执行就报错了,说不支持,就去各种反编译出来看,原来带参数的操作是不在一起的,要分别加入Iterator,这么设计也是有点醉了。

不多说,代码列出来看看,有点内存问题,不过懒得改了。

CompileUitl.java  可以直接运行

package com.common.util;

import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class CompileUtil {

	private static String KEY_JAVA_FILE = "javaFile";
	private static String KEY_OTHER_FILE = "otherFile";

	/**
	 * compile the class file under the given path:src,and copy the others to the dest path.
	 * the hidden file is not supported
	 * 
	 * @param src the path your class file exist
	 * @param dest  the output path
	 * @param options javac compile option,you can refer to @{com.sun.tools.javac.main.OptionName},if the option has values, just add it to the iterator separately
	 * @param charSet your file encoding,like "UTF-8"
	 * @throws Exception
	 */
	public static void compileAndCopyFiles(String src, String dest, List<String> options,String charSet) throws Exception {
		System.out.println("start compileAndCopyFiles.....");
		long start = System.currentTimeMillis();
		FileUtil.mkDirs(dest);
		Map<String, List<File>> allFiles = getFiles(src);
		List<File> files = allFiles.get(KEY_JAVA_FILE);
		List<File> otherFiles = allFiles.get(KEY_OTHER_FILE);

		JavaCompiler cmp = ToolProvider.getSystemJavaCompiler();
		StandardJavaFileManager fileManager = cmp.getStandardFileManager(null, null, Charset.forName(charSet));

		Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(files);

		cmp.getTask(null, fileManager, null, options, null, compilationUnits).call();
		fileManager.close();

		copyOtherFiles(otherFiles, src, dest);
		System.out.println("end compileAndCopyFiles.Files amount:"+allFiles.size()+".Total spend time : "+(System.currentTimeMillis()-start)/1000+" s");
	}

	private static void copyOtherFiles(List<File> files, String src, String dest) throws Exception{
		for (File file : files) {
			String fileAbsolutePath = file.getAbsolutePath();
			String destPath = dest + fileAbsolutePath.substring(src.length(), fileAbsolutePath.length());
			FileUtil.copy(fileAbsolutePath, destPath);
		}
	}

	private static Map<String, List<File>> getFiles(String src) {
		List<File> files = FileUtil.getAllFiles(src);
		String suffix = ".java";
		Map<String, List<File>> map = new HashMap<String, List<File>>();
		List<File> javaFile = new ArrayList<File>();
		List<File> otherFile = new ArrayList<File>();
		for (File file : files) {
			String fileName = file.getName();
			if (fileName.endsWith(suffix)) {
				javaFile.add(file);
			} else {
				otherFile.add(file);
			}
		}
		map.put(KEY_JAVA_FILE, javaFile);
		map.put(KEY_OTHER_FILE, otherFile);
		return map;
	}
	
	public static void main(String ars[]) throws Exception{
		System.out.println(System.getProperty("user.dir"));
		String src=System.getProperty("user.dir") + File.separator +"src";
		String dest=System.getProperty("user.dir") + File.separator +"classes"+File.separator+"me";
		List<String> options = new ArrayList<String>();
		//options.add("-verbose");
		options.add("-d");
		options.add(dest);
		CompileUtil.compileAndCopyFiles(src, dest, options, "GBK");
				
	}

}
FileUtil.java  辅助类

package com.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {

	public static List<File> getAllFiles(String path) {
		List<File> files = new ArrayList<File>();
		File file = new File(path);
		if (file.exists() && !file.isHidden()) {
			if (file.isDirectory()) {
				File[] fs = file.listFiles();
				for (File f : fs) {
					if (!file.isHidden()) {
						if (f.isDirectory()) {
							files.addAll(getAllFiles(path + File.separator
									+ f.getName()));
						}
						if (f.isFile()) {
							files.add(f);
						}
					}
				}

			} else if (file.isFile()) {
				files.add(file);
			}
		}
		return files;
	}

	public static void copy(String from, String to) throws Exception {
		InputStream in = new FileInputStream(from);
		OutputStream out = new FileOutputStream(to);

		byte[] buff = new byte[1024];
		int len = 0;
		while ((len = in.read(buff)) != -1) {
			out.write(buff, 0, len);
		}
		in.close();
		out.close();
	}

	public static void mkDirs(String path) {
		File destFile = new File(path);
		if (!destFile.exists()) {
			destFile.mkdirs();
		}
	}

}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果 JavaCompiler 找不到程序包,可能是由于编译选项中未正确指定 Maven 依赖包的路径,或者依赖包未正确加载。请确保按照以下步骤进行操作: 1. 确保您的项目已经正确配置了 Maven 依赖项。您可以在项目的 `pom.xml` 文件中定义所需的依赖项,并使用 Maven 构建项目。 2. 确保您的项目已经成功构建,并且所有的依赖包已经下载并位于本地 Maven 仓库中。 3. 在获取 Maven 依赖包路径时,请确保您使用的是正确的方法。以下是一种获取 Maven 依赖包路径的方法: ```java private static String getMavenClasspath() { MavenCli mavenCli = new MavenCli(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(outputStream); int result = mavenCli.doMain(new String[]{"dependency:build-classpath"}, "path/to/your/project", printStream, printStream); if (result == 0) { String classpath = new String(outputStream.toByteArray(), StandardCharsets.UTF_8); return classpath.trim(); } else { throw new RuntimeException("Failed to retrieve Maven classpath."); } } ``` 上述代码使用 MavenCli 类来执行 Maven 命令 `dependency:build-classpath`,并捕获输出结果作为 Maven 依赖包路径。 4. 在编译选项中正确指定 Maven 依赖包路径,并确保它们位于正确的位置: ```java List<String> options = new ArrayList<>(); options.add("-classpath"); options.add(getMavenClasspath()); ``` 请确保替换相应的文件路径和类名。 通过以上步骤,您应该能够在 JavaCompiler 中正确引用和编译 Maven 中的依赖包。如果问题仍然存在,请检查您的 Maven 依赖项配置和项目构建过程,确保依赖包正确加载和可用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值