練習 2017-08-21 去除文檔中的注釋行

来源:互联网 发布:高韶青 离开中国 知乎 编辑:程序博客网 时间:2024/06/08 06:33
package removeComments;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;




//去除文檔中的注釋
public class RemoveCommentsDemo {
public static void main(String[] args) {
File javaFile = new File("D:/javaFile.txt");

removeComments(javaFile);
}

public static void removeComments(File javaFile){
String str = null;
StringBuilder sb = new StringBuilder(100);
try(
BufferedReader in = new BufferedReader(new FileReader(javaFile));
){
while((str=in.readLine())!= null){
if(!str.trim().startsWith("//")){
sb.append(str).append("\r\n");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try(
PrintWriter out = new PrintWriter(new FileWriter(javaFile));
){
out.println(sb.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}