/**
* 大文件小说分章节读取
*
* @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);
}
}