为批量java文件添加license

以前为文件添加apache2.0 license的时候随手写了一个,但后来删了,现在又重新写了一个,这里备份下

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class T {

	// java文件主目录
	private static final File dir = new File("C:/workspace2/blog/src/main/java/me");
	// license内容
	private static final String license;

	static {
		try {
			license = new String(Files.readAllBytes(Paths.get("h:/license.txt"))) + "\r\n";
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public static void main(String[] args) throws IOException {
		Files.walk(dir.toPath()).filter(Files::isRegularFile).filter(T::noLicense).forEach(T::writeLicense);

		System.out.println("done");
	}

	// 文件头部添加license
	private static void writeLicense(Path path) {
		try (BufferedWriter bw = Files.newBufferedWriter(path, StandardOpenOption.WRITE)) {
			String content = new String(Files.readAllBytes(path));
			bw.write(license);
			bw.write(content);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	// 判断文件是否有license
	private static boolean noLicense(Path path) {
		try (BufferedReader reader = Files.newBufferedReader(path)) {
			String line;
			while ((line = reader.readLine()) != null) {
				line = line.trim();
				if (line.startsWith("package")) {
					return true;
				}
				if (line.startsWith("import ")) {
					return true;
				}
				if (line.contains("Copyright ")) {
					return false;
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return true;
	}

}

添加完刷新下项目就可以了。