正则表达式读取小说(txt文本)的章节

直接贴代码

package Chapter;

import java.io.File;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.InputStreamReader;

/**
 * @author 下一季
 *
 */

class BookContent {

	int chapterId;// 章节id
	int bookId;// 图书id
	String chapterName;// 章节名
	String content;// 当前章节内容
	int order;// 章节序号

	public BookContent(int chapterId, int bookId, String chapterName, int order) {// 构造方法(缺少一个成员变量)

		this.order = order;
		this.bookId = bookId;
		this.chapterId = chapterId;
		this.chapterName = chapterName;

	}

}

public class ParseBookContentUtil {

	public static void main(String[] args) {
		JdbcConnection.insertSQL(parse(1, "C://Users//下一季//Desktop//一念永恒.txt"));// 把获取后的list插入到SQLserver
	}

	public static int idCount = 1;// 手动增加 章节id ,导入多个小说文件时,避免id重复

	public static ArrayList<BookContent> parse(int BookId, String path) {

		ArrayList<BookContent> list = null;

		try {

			File file = new File(path);
			if (!file.isFile() || !file.exists()) {
				return null;
			}

			InputStreamReader read = new InputStreamReader(new FileInputStream(file), "GBK");
			BufferedReader bufferedReader = new BufferedReader(read);

			int count = 1;
			String lineTxt = null;
			list = new ArrayList<>();

			StringBuilder lastBuilder = null;
			BookContent lastBookContent = null;

			while ((lineTxt = bufferedReader.readLine()) != null) {

				lineTxt = lineTxt.trim();

//				正则表达式:我的小说章节名是以 ###开头,###结尾 ,所以用第二个更好
				Pattern p = Pattern.compile("(第\\S*)[章节卷集部篇回](\\s)(\\S*)[^#]");
//				Pattern p = Pattern.compile("(###)(.*)(###)");
				Matcher matcher = p.matcher(lineTxt);

				if (matcher.find()) {

					if (lastBookContent != null) {
						lastBookContent.content = lastBuilder.toString();
						list.add(lastBookContent);
//						System.out.println(lastBuilder.toString());// 输出当前的章节内容,建议设置输出长度
					}

					BookContent newBookContent = new BookContent(idCount++, BookId, matcher.group(), count++);
//					System.out.println(newBookContent.chapterName);// 输出当前的章节名

					lastBuilder = new StringBuilder();
					lastBookContent = newBookContent;

				} else if (lastBuilder != null) {
					lastBuilder.append(lineTxt + "\n");
				}

			}

//			以防最后一个章节无法读取
			if (lastBuilder != null) {
				lastBookContent.content = lastBuilder.toString();
				list.add(lastBookContent);
			}

			bufferedReader.close();

		} catch (Exception e) {
			System.out.println("文件读取失败");
			e.printStackTrace();
		} finally {
			return list;
		}

	}

}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值