读文件时去掉注释部分内容方法

处理的重点就是如何判断和删除两行注释中间的不是以"#"或者"~"开头的注释行,草草写了段代码,对于楼主给的那段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();
                }
            }
        }
    }
}
但是还有个问题就是该程序没有考虑到如果在正文以后再次出现注释行的情况,如果用本程序处理的话,就会错误的把正文也作为注释删除,如果有高人的话还望能够不吝赐教。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值