给java代码加一行PACKAGE(在文件头添加一行)

给java代码加一行PACKAGE(在文件头添加一行)

 

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class Tet {
    private static String initDir;
    
    private void getFiles(String dir) throws IOException{
	File file=new File(dir);
	File[] files=file.listFiles();
	for (File file2 : files) {
	    if(file2.isDirectory()){
		getFiles(file2.getPath());
	    }else if(file2.isFile()&&file2.getName().endsWith("java")){
		modify(file2.getPath(), dir);
	    }
	}
    }
    
    private void modify(String filePath,String dir) throws IOException{
	System.out.println(filePath);
	File file=new File(filePath);
	    BufferedReader br = new BufferedReader(new InputStreamReader(
		    new FileInputStream(file)));
	    List list = new ArrayList();
	    String f2=file.getParent();
	    System.out.println(f2+"\n"+f2.replace(initDir, ""));
	    String packageString="package "+f2.replace(initDir, "").replace("\\", ".").replaceFirst(".", "")+";";
	    list.add(packageString);
	    while (true) {
		String str = br.readLine();
		if (str == null)
		    break;
		int index = str.indexOf(packageString);
		if (index != -1) {
//		    str.replace(packageString, "");
		    continue;
		}
		list.add(str);

	    }
	    br.close();

	    PrintWriter pw = new PrintWriter(file);
	    for (int i = 0; i < list.size(); i++) {
		String str = (String) list.get(i);
		pw.println(str);
	    }
	    pw.close();
    }
    
    public static void main(String[] args) {
	initDir="D:\\Work\\Workspace64\\Think in Java 4 code\\src";
	try {
	    new Tet().getFiles(initDir);
	} catch (IOException e) {
	    e.printStackTrace();
	}
    }
}

 

你可能感兴趣的:(package)