章节选择器

章节选择器采用正则表达式来实现,本程序是用自己的小说文档来实现的,所以编译模式的设置要根据自己采用什么样的文档:

public class Test06 {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("^\\s*第[一二三四五六七八九十零百千万]+章");//编译模式
        try (RandomAccessFile raf = new RandomAccessFile("res/Utf.txt", "rw")) {
            byte[] bytes = new byte[102400];
            int length;
            Map<Integer, Long> map = new HashMap<>();
            int index = 1;
            while ((length = raf.read(bytes)) != -1) {
                String unicode = new String(bytes, 0, length, "Unicode");
                String[] split = unicode.split("\r\n");
                for (int i = 0; i < split.length - 1; i++) {
                    Matcher matcher = pattern.matcher(split[i]);
                    if (matcher.find()) {
                        System.out.println(split[i]);
                        map.put(index++,
                                raf.getFilePointer() -
                                        unicode.substring(unicode.indexOf(split[i])).getBytes("Unicode").length);
                    }
                }
                if (length == 102400) {
                    raf.seek(raf.getFilePointer() - split[split.length - 1].getBytes("Unicode").length);
                }
            }
            BufferedReader sbr= new BufferedReader(new InputStreamReader(System.in));
            System.out.println(index);
            int chapter = Integer.parseInt(sbr.readLine());
            Long current = map.get(chapter);
            Long next = map.get(chapter + 1);
            raf.seek(current);
            if (next == null) {
                while ((length = raf.read(bytes)) != -1) {
                    System.out.print(new String(bytes, 0, length, "Unicode" ));
                }
            } else {
                byte[] b = new byte[(int) (next - current)];
                raf.read(b);
                System.out.println(new String(b, "Unicode"));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
运行结果:


输入章节数字:12


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值