大文件小说分章节读取
  mJ4yWAKdRNcf 2023年12月19日 16 0


/**
 * 大文件小说分章节读取
 *
 * @author Mi
 */
public class NovelSplitText {
    public static void main(String[] args) {

        String filePath = "D:/神墓.txt";

        readTextFile(filePath, new ChapterCallback() {
            @Override
            public void onChapterFound(String title, String content) {
                System.out.println("Found chapter: " + title);
                System.out.println("Chapter content:\n" + content);
            }
        });
    }

    // 读取文本文件并使用回调方式处理章节标题和内容
    private static void readTextFile(String filePath, ChapterCallback callback) {
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            StringBuilder chapterContent = new StringBuilder();
            String currentTitle = null;

            while ((line = reader.readLine()) != null) {
                if (isChapterTitle(line)) {
                    // 如果遇到新的章节标题,则调用回调方法处理上一章节的标题和内容
                    if (currentTitle != null) {
                        callback.onChapterFound(currentTitle, chapterContent.toString());
                        chapterContent.setLength(0); // 清空 chapterContent
                    }
                    currentTitle = line; // 保存新的章节标题
                } else {
                    // 将行内容添加到章节内容中
                    chapterContent.append(line).append("\n");
                }
            }

            // 处理最后一个章节的内容
            if (currentTitle != null) {
                callback.onChapterFound(currentTitle, chapterContent.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 判断是否为章节标题
    private static boolean isChapterTitle(String line) {
        Pattern pattern = Pattern.compile("第.{1,8}[章节回][\\s\\n]");
        Matcher matcher = pattern.matcher(line);
        return matcher.find();
    }

    // 定义回调接口
    interface ChapterCallback {
        void onChapterFound(String title, String content);
    }
}


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年12月19日 0

暂无评论

推荐阅读
mJ4yWAKdRNcf