天天看點

給java檔案批量添加License資訊

package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/**
 * 給java檔案批量添加License資訊
 * @author tanghc
 *
 */
public class Copyright {

	private static String lineSeperator = System.getProperty("line.separator");
	private static String encode = "UTF-8";
	
	private String folder;
	private String copyright;
	
	/**
	 * @param folder java檔案夾
	 * @param copyright 版權内容
	 */
	public Copyright(String folder, String copyright) {
		this.folder = folder;
		this.copyright = copyright;
	}
	
	public static void main(String[] args) throws IOException {
		// 從檔案讀取版權内容
		// 在D盤建立一個copyright.txt檔案,把版權内容放進去即可
		String copyright = readCopyrightFromFile("D:/copyright.txt");
		// 存放java檔案的檔案夾,必須是檔案夾
        String folder = "D:/workspace-sts-3.8.4.RELEASE/easymybatis/src";
        
		new Copyright(folder, copyright).process();
		
		System.out.println("end.");
	}
	
	public void process() {
		this.addCopyright(new File(folder));
	}

	private void addCopyright(File folder) {
		File[] files = folder.listFiles();

		if (files == null || files.length == 0) {
			return;
		}

		for (File f : files) {
			if (f.isFile()) {
				doAddCopyright(f);
			} else {
				addCopyright(f);
			}
		}
	}

	private void doAddCopyright(File file) {
		String fileName = file.getName();
		boolean isJavaFile = fileName.toLowerCase().endsWith(".java");
		if(isJavaFile) {
			try {
				this.doWrite(file);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void doWrite(File file) throws IOException {
		
        
		StringBuilder javaFileContent = new StringBuilder();
		String line = null;
		// 先添加copyright到檔案頭
		javaFileContent.append(copyright).append(lineSeperator);
		// 追加剩餘内容
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encode));
        while ((line = br.readLine()) != null) {
        	javaFileContent.append(line).append(lineSeperator);
        }  
        
        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), encode);
       	writer.write(javaFileContent.toString());
       	writer.close();
        br.close();  
	}
	
	private static String readCopyrightFromFile(String copyFilePath) throws IOException {
		StringBuilder copyright = new StringBuilder();
		
		String line = null;
		
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(copyFilePath), encode));
       
		while ((line = br.readLine()) != null) {
        	copyright.append(line).append(lineSeperator);
        }
        br.close();
        
        return copyright.toString();
	}

}