处理的重点就是如何判断和删除两行注释中间的不是以"#"或者"~"开头的注释行,草草写了段代码,对于楼主给的那段some.txt能够正常处理
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class DelectComments {
public static void main(String rags[]) {
File f = new File("D://Hello.txt");
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(f));
boolean flag1 = false;// #
boolean flag2 = false;// ~
String content = "";
// last output content
ArrayList<String> outputContents = new ArrayList<String>();
// the number of lines that between 2 comments lines start with "#" or "~"
int commentsLineNum = 0;
while ((content = br.readLine()) != null) {
// the line is comments and start with "#"
if (content.startsWith("#")) {
// delete the comments lines between 2 comments lines start with "#"
if (flag1) {
for (int i = 0; i < commentsLineNum; i++) {
outputContents.remove(outputContents.size() - 1);
}
commentsLineNum = 0;
} else {
flag1 = true;
}
// the line is comments and start with "~"
} else if (content.startsWith("~")) {
// delete the comments lines between 2 comments lines start with "~"
if (flag2) {
for (int i = 0; i < commentsLineNum; i++) {
outputContents.remove(outputContents.size() - 1);
}
commentsLineNum = 0;
} else {
flag2 = true;
}
} else {
outputContents.add(content);
commentsLineNum++;
}
}
// output the text
for (String outputContent : outputContents) {
System.out.println(outputContent);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
但是还有个问题就是该程序没有考虑到如果在正文以后再次出现注释行的情况,如果用本程序处理的话,就会错误的把正文也作为注释删除,如果有高人的话还望能够不吝赐教。
读文件时去掉注释部分内容方法
最新推荐文章于 2023-06-15 15:17:55 发布