import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RemoveComments {
private static File file = null;
private static File tempFile = null;
/**
* @param fileName 文件名也可能是文件夹名
* @param formatter 文件格式
*/
public static void removeComment(String fileName,String formatter){
if(formatter.equals("java")){
file = new File(fileName);
try {
BufferedReader read = new BufferedReader(new FileReader(file));
StringBuffer buffer = new StringBuffer();
String lineStr = "";
while((lineStr=read.readLine())!=null){
String temp=testRemoveComment(lineStr);
buffer.append(temp+"\r\n");
}
read.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(buffer.toString());
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* @param source 用正则表达式过滤的字符串
* @return 过滤后的字符串
*/
public static String testRemoveComment(String source){
Pattern pattern = Pattern.compile("\\/\\s*\\*.*\\*\\s*[~.]*\\/");
Matcher matcher = pattern.matcher(source);
return matcher.replaceAll("");
}
/**
* @param fileName 文件夹的名字
* 遍历整个文件树
*/
public static void bianli(String fileName){
file = new File(fileName);
File[] files = file.listFiles();
for(int i=0;i<files.length;i++){
if(files[i].getName().endsWith("java")||
files[i].getName().endsWith("properties")||
files[i].getName().endsWith("dtd")){
removeComment(files[i].getAbsolutePath(),
files[i].getAbsolutePath().substring(files[i].getAbsolutePath().length()-4));
}else{
System.out.println(files[i].getName());
bianli(files[i].getAbsolutePath());
}
}
}
public static void main(String[] args) {
bianli("C:\\Documents and Settings\\Administrator\\桌面");
}
}