Java应用之删除注释和英文大小写转换

    最近写博客上传代码的时候,用于代码里写了些很随意的注释,想把注释全部删掉,在网上找了下代码,发现很多都是使用正则表达式替换的,如

   

Map<String, String> patterns = new HashMap<String, String>();
		patterns.put("([^:])\\/\\/.*", "$1");// 匹配在非冒号后面的注释,此时就不到再遇到http://
		patterns.put("\\s+\\/\\/.*", "");// 匹配“//”前是空白符的注释
		patterns.put("^\\/\\/.*", "");
		patterns.put("^\\/\\*\\*.*\\*\\/$", "");
		patterns.put("\\/\\*.*\\*\\/", "");
		patterns.put("/\\*(\\s*\\*\\s*.*\\s*?)*\\*\\/", "");

    使用过程中发现,这样替换是有问题的,如下上测试例子:

   

/**
 * 这是注释//嵌套注释
 * 
 * @author Administrator 测试 修改日期:2014-02-17
 */
public class 测试注释 {

	/**
	 * 测试注释 <[CDATA\**测试]>
	 * 
	 * @param fileName
	 * @param outFileName
	 */
	public void TestFile(String fileName, String outFileName) {
		/**
		 * 输出语句测试
		 */
		System.out.println("/*我是正常内容*/");// 测试注释L16
		/* 测试注释L17 */
		System.out.println("//注释哈哈");
		//今天是2014-02-17
		System.out.println("/*" +
		                            "* 测试" + //注释,能删除吗
				                   /*测试L20*/ "注释*/");
	}
}

   这种正则替换的结果是:

  
Java应用之删除注释和英文大小写转换_第1张图片
     正常内容也被替换掉了,所以在替换之前要先判断是否是在" "里面。

     在网上找了个靠谱点的代码,先上参考链接:

    

http://jdksummer.iteye.com/blog/976707 

    他的方法是先判断是否在""内再替换。如下:

   

 public void run(String inputF,String outputF) throws IOException {
        this.inputFile=inputF;
        this.outputFile=outputF;

        File file = new File(inputFile);
        if (!file.exists() || file.isDirectory()) {
            throw new FileNotFoundException();
        }

        // 写出文件初始
        File writefile = new File(outputFile);
        if (!writefile.exists()) {
            writefile.createNewFile();
        }
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(writefile)));

        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        boolean flagFindhead = true; // 多行注释找头
        boolean markFinded = false;  //是否发现双引号
        int i = 0;
        String temp = null;
        temp = br.readLine();
        while (temp != null) {
            if (temp != null) {
                StringBuilder sb = new StringBuilder();
                for (i = 0; i < temp.length(); i++) {
                                  //此处一定要注意判断是否在双引号内
                    if (temp.charAt(i) == '/' && !(i > 0 && markFinded)) {            
                        if (i + 1 < temp.length() && temp.charAt(i + 1) == '/') {  
                            break;
                        } else if (flagFindhead && i + 1 < temp.length()
                                && temp.charAt(i + 1) == '*') {
                            flagFindhead = false;
                            for (int j = i + 1; j < temp.length(); j++) {
                                i = j;
                                if (temp.charAt(j) == '*'
                                        && (j + 1 < temp.length() && temp.charAt(
                                                                 j + 1) == '/')) {
                                    flagFindhead = true;
                                    i += 2;
                                    break;
                                }
                            }
                        }
                    }

                    if (!flagFindhead && temp.charAt(i) == '*'
                            && (i + 1 < temp.length() && temp.charAt(i + 1) == '/')) {
                        flagFindhead = true;
                        i += 2;
                    }
                    if (flagFindhead && i < temp.length()) {
                         //发现双引号“ ,置发现标志为true,即进入了双引号的范围
                        if(temp.charAt(i)=='\"' && markFinded==false)           
                            markFinded=true;
                        //发现双引号” ,置发现标志为false,即已经出了双引号的范围
                        else if(temp.charAt(i)=='\"' && markFinded==true) 
                            markFinded=false;
                        sb.append(temp.charAt(i));
                    }
                }
                temp = sb.toString();
            }
            if (temp.length() > 0) {
                bw.write(temp + "\r\n");
                bw.flush();
            }
            temp = br.readLine();
        }

        br.close();
        bw.close();
    }

   使用后发现文件中出现很多的空白,我修改了下,把空白行去掉了。

  

public void delFileComment(String inputFile, String outputFile,String charSet)
			throws IOException {
		if(charSet==null)
		{
			charSet="utf-8";
		}
		File file = new File(inputFile);
		if (!file.exists() || file.isDirectory()) {
			throw new FileNotFoundException();
		}
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream(outputFile),charSet));
		BufferedReader br = new BufferedReader(new InputStreamReader(
				new FileInputStream(file),charSet));
		boolean flagFindhead = true; // 多行注释找头
		boolean markFinded = false; // 是否发现双引号
		int i = 0;
		String temp = null;
		temp = br.readLine();
		while (temp != null) {
			if (temp != null) {
				StringBuilder sb = new StringBuilder();
				for (i = 0; i < temp.length(); i++) {
					// 此处一定要注意判断是否在双引号内
					if (temp.charAt(i) == '/' && !(i > 0 && markFinded)) {
						if (i + 1 < temp.length() && temp.charAt(i + 1) == '/') {
							break;
						} else if (flagFindhead && i + 1 < temp.length()
								&& temp.charAt(i + 1) == '*') {
							flagFindhead = false;
							for (int j = i + 1; j < temp.length(); j++) {
								i = j;
								if (temp.charAt(j) == '*'
										&& (j + 1 < temp.length() && temp
												.charAt(j + 1) == '/')) {
									flagFindhead = true;
									i += 2;
									break;
								}
							}
						}
					}
					if (!flagFindhead
							&& temp.charAt(i) == '*'
							&& (i + 1 < temp.length() && temp.charAt(i + 1) == '/')) {
						flagFindhead = true;
						i += 2;
					}
					if (flagFindhead && i < temp.length()) {
						// 发现双引号“ ,置发现标志为true,即进入了双引号的范围
						if (temp.charAt(i) == '\"' && markFinded == false)
							markFinded = true;
						// 发现双引号” ,置发现标志为false,即已经出了双引号的范围
						else if (temp.charAt(i) == '\"' && markFinded == true)
							markFinded = false;
						sb.append(temp.charAt(i));
					}
				}
				temp = sb.toString();
			}
			// 把空白换成"",然后使用trim过滤掉。
			temp = temp.replaceAll("\\s*\n", "");
			if (temp.trim().length() > 0) {
				bw.write(temp + "\r\n");
				bw.flush();
			}
			temp = br.readLine();
		}
		br.close();
		bw.close();
	}

    测试结果如下:

   
Java应用之删除注释和英文大小写转换_第2张图片
    结果很正确。

   

    写博客中遇到的另一个问题是我的SQL语句有时候没注意,一会大写,一会小写,一点也不规范,所以自己写了个简单的类,把文件转换大写或者小写。

   

public void convertContentTLowerCase(String fileName, String chartSet) {
		convertContent(fileName, true, chartSet);
	}

	public void convertContentTUpperCase(String fileName, String chartSet) {
		convertContent(fileName, false, chartSet);
	}

	public void convertContent(String fileName, boolean isLower, String chartSet) {
		if (chartSet == null) {
			chartSet = "utf-8";
		}
		String outFileName = fileName.substring(0, fileName.lastIndexOf("."))
				+ "_result" + fileName.substring(fileName.lastIndexOf("."));
		BufferedReader br = null;
		BufferedWriter bw = null;
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(
					fileName), chartSet));
			bw = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(outFileName), chartSet));
			String tempStr = null;
			while ((tempStr = br.readLine()) != null) {
				if (isLower) {
					tempStr = tempStr.toLowerCase();
				} else {
					tempStr = tempStr.toUpperCase();
				}
				bw.write(tempStr + "\r\n");
			}
			bw.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null) {
					br.close();
				}
				if (bw != null) {
					bw.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

   上面要2个路径是因为我我想读一行写一行 ,核心就是String的toUpperCase。

   

      上面的代码都很简单,这是我自己用的,请不要询问我有什么意义,对我我用就是意义,谢谢。

   

      全文完。

   

 

你可能感兴趣的:(Java英文大小写转换)