【原创】Copy源文件,并去掉注释
发表于:2007-07-01来源:作者:点击数:
标签:
/** DelComment. java ** Copy this file to Copy.java, * and get rid of the comments.** Author:李文雄。033534026* Class :电子政务** Time:04-08-2005** 可以把一些//和/*嵌套的注释也能够去掉,* 另外也可以区别出那些是字符串的字符,而不是注释。*
/** DelComment.
java * * Copy this file to Copy.java, * and get rid of the comments. * * Author:李文雄。033534026 * Class :电子政务 * * Time:04-08-2005 * * 可以把一些//和/*嵌套的注释也能够去掉, * 另外也可以区别出那些是字符串的字符,而不是注释。 * 完成的功能比较好 * */package Class;import java.io.*;
public class DelComment{ private static void outLine(BufferedWriter out,String line ,int n){ // Used to write to the outfile String s = "第" + n + "行:"; line = s + line; try{ out.write(line); out.newLine(); } catch(IOException e){ e.printStackTrace(); } } public static void main(String[] args){ //Main Function int n = 0; // note the line number String line = ""; //Used to load the string String temp = ""; int cmtIndex0 = -1; //用来标记 字符串引号 " int cmtIndex4 = -1; int cmtIndex1 = -1; //用来标记 注释符号 // int cmtIndex2 = -1; //用来标记 注释符号 /* */ boolean isCmt1 = false; //用来标记 注释符号 // boolean isCmt2 = false; //用来标记 注释符号 /* */ try{ BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("DelComment.java"))); //BufferedWriter out = new BufferedWriter(new FileWriter("copy.java")); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("copy.java"))); while((temp = in.readLine()) != null){ cmtIndex2 = temp.indexOf("*/"); if((cmtIndex2 != -1) && isCmt2){ isCmt2 = false; line = temp.substring(cmtIndex2+2); n++; outLine(out,line,n); continue; } if(isCmt2) continue; cmtIndex0 = temp.indexOf("\""); //出现左引号"的位置 cmtIndex1 = temp.indexOf("//"); cmtIndex2 = temp.indexOf("/*"); cmtIndex4 = temp.indexOf("\"",cmtIndex0+1); //出现右引号"的位置 if( !((cmtIndex0 < cmtIndex1) && (cmtIndex1 < cmtIndex4)) ){ // "//" 不是在两个引号之间 if(cmtIndex1 != -1){ if( (cmtIndex1 < cmtIndex2) || (cmtIndex2 == -1)) if(cmtIndex1 > 0){ line = temp.substring(0,cmtIndex1); n++; outLine(out,line,n); continue; } } } if( !((cmtIndex0 < cmtIndex2) && (cmtIndex2 < cmtIndex4)) ){ // "/*" 不是在两个引号之间 if(cmtIndex2 != -1){ if(cmtIndex2 > 0){ line = temp.substring(0,cmtIndex2); n++; outLine(out,line,n); } isCmt2 = true; continue; } } n++; outLine(out,temp,n); } in.close(); out.close(); }catch(EOFException e){} //catch the exception catch(IOException e){ e.printStackTrace(); } catch(Exception e){ e.printStackTrace(); } //********* Those below just for test of "Get rid of comment" String str1 = "// This is just to test about (//)"; String str2 = "/* This is just to test about (/* */) */"; System.out.println(str1); System.out.println(str2); }}
==>输出结果:
http://blog.csdn.net/horisly/archive/2005/04/08/340159.aspx
原文转自:http://www.ltesting.net