import java.io.*;
import java.util.HashMap;
import java.util.regex.*;
public class DelRem
{
public static void main(String args[])
{
DelRem delRem = new DelRem();
String dirName = "E:/workspace/SwingDemo/src/SimpleTableDemo.java";
File oldFile = new File(dirName);
/******************** 判断当前的路径是文件还是目录 ********************/
if (oldFile.isDirectory())
{
delRem.findFileInDir(dirName);
}
else
{
delRem.delRemark(dirName);
}
}
public void delRemark(String dirName)
{
try
{
/************* 备份带有注释的源程序文件,并生成空文件 *************/
File srcFile = new File(dirName);
File bakFile = new File(dirName + ".bak");
bakFile.createNewFile();
/************* 源程序文件中删除注释代码过程在这里处理 ************/
/*************** 把注释以外的代码复制到新建立的文件之中 **********/
BufferedReader br = new BufferedReader(new FileReader(srcFile));
BufferedWriter bw = new BufferedWriter(new FileWriter(bakFile));
Pattern slash_star_start = Pattern.compile("/\\*.*"); // /*.....
Pattern star_slash = Pattern.compile("^.*\\*/"); // .......*/
Pattern slash_star_both = Pattern.compile("/\\*.*\\*/"); // /*.....*/
Pattern slash2 = Pattern.compile("\\s{0,}//[^;+]*$"); // //....
Pattern strPattern=Pattern.compile("\".*\"");
Matcher mat;
int i = 0;
String s;
boolean note = false;
while ((s = br.readLine()) != null)
{
//替换字符串
s = s.replaceAll(strPattern.pattern(), "");
// 处理/*...*/之间的注释
s = s.replaceAll(slash_star_both.pattern(), "");
// d处理//后面的注释
mat = slash2.matcher(s);
if (mat.find() && note == false)
{
s = s.substring(0, mat.start());
if (s.trim().length() == 0){
bw.newLine();
continue;
}
bw.write(s);
bw.newLine();
continue;
}
// 处理*/之前的注释
mat = star_slash.matcher(s);
if (mat.find())
{
note = false;
s = s.substring(mat.end());
if (s.trim().length() == 0)
{
bw.newLine();
continue;
}
}
if (note == true)
{
bw.newLine();
continue;
}
// d处理/*之后的注释
mat = slash_star_start.matcher(s);
if (mat.find())
{
note = true;
s = s.substring(0, mat.start());
if (s.trim().length() == 0)
{
bw.newLine();
continue;
}
}
bw.write(s);
bw.newLine();
}
br.close();
bw.close();
/*************** 删除有注释的源文件并把无注释文件名改名 *************/
/*srcFile.delete();
bakFile.renameTo(new File(dirName));
*/
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void findFileInDir(String dirName)
{
DelRem delRem = new DelRem();
File file = new File(dirName);
String nameFiles[] = file.list();
for (int i = 0; i < nameFiles.length; i++)
{
String fileName = dirName + "\\" + nameFiles[i];
File newFile = new File(fileName);
if (newFile.isDirectory())
{
delRem.findFileInDir(fileName);
}
else
{
delRem.delRemark(fileName);
}
}
}
}