TXT格式小说实现分章节

最近一直在手机上看小说,于是想能不能在电脑上看,在网上查了一下资料,主要参考这一篇https://blog.csdn.net/inowcome/article/details/6047661,写了一个小程序,实现把一个TXT格式的小说每一章做成一个html文件,还有一个章节列表。

这是原小说


这是生成的html文件



章节列表


实现方式很简单,以下是源代码

package com.sjm.chapterSeparater;


import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;


public class Separater {
/**
* 生成小说文件夹
* @param novel
* @return 成功生成返回文件夹名,已存在返回null
*/
private static String genarateFolder(File novel) {
if(!novel.isFile() || !novel.getAbsolutePath().endsWith(".txt")) {
return null;
}
String novelName = novel.getAbsolutePath();
String folderName = novelName.substring(0, novelName.indexOf(".txt"));
File folder = new File(folderName);
if (!folder.exists()) {
folder.mkdirs();
return folderName;
}
return null;
}
    /**
     * 输出html文件
     * @param bodyContent
     * @param currentFileName
     * @param currentPageIndex
     * @throws Exception
     */
    private static void generateChapterHtmlFile(int currentPageIndex,String content,List<String> chapterList,String folderName)throws Exception {
         String pageContent="<html><head>"
                             +"<meta http-equiv='content-type' content='text/html;charset=utf-8'>"
                             +"<title>"+chapterList.get(currentPageIndex)+"</title>"
                             +"<script type=\"text/javascript\">" 
                             +"window.onload = function(){"
                             +"//去掉默认的contextmenu事件,否则会和右键事件同时出现。\r\n"  
                             +"document.oncontextmenu = function(e){"  
                             +"e.preventDefault();"
                             +"};"
                             +" document.getElementById(\"body\").onmousedown = function(e){"
                             +" if(e.button ==2){"
                             +"window.open('"+chapterList.get(currentPageIndex==chapterList.size()-1?chapterList.size()-1:currentPageIndex+1)+".html','_self')"
                             +"}else if(e.button ==0){"
                             +"window.open('"+chapterList.get(currentPageIndex==0?0:currentPageIndex-1)+".html','_self')"
                             +"}else if(e.button ==1){"
                             +"window.open('章节目录.html','_self');}}}" 
                             +"</script>"
                             +"</head><body bgcolor='#e6f3ff' id='body'>"
                             +"<h1 align='center'>"+chapterList.get(currentPageIndex)+"</h1>"
                             +"<div style='line-height:40px;font-size:24px;width: 50%;margin :auto'>"+content+"</div>"
                             +"</br>"
                             +"<table align='center'>"
                             +"<tr>"
                             +"<td><a href='"+chapterList.get(currentPageIndex==0?0:currentPageIndex-1)+".html'>上一页</a></td>"
                             +"<td><a href='contents.html'>目录</a></td>"
                             +"<td><a href='"+chapterList.get(currentPageIndex==chapterList.size()-1?chapterList.size()-1:currentPageIndex+1)+".html'>下一页</a></td>"
                             +"</tr>"
                             +"</table>"
                             +"</body></html>";
         String filePath=folderName+"\\"+chapterList.get(currentPageIndex)+".html";
         PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter(filePath)));
         out.print(pageContent);
         out.flush();
         out.close();
    }
    /**
     * 获取章节列表
     * @param novel
     * @throws Exception
     */
    private static List<String> getChapterList(File novel) throws Exception {
    List<String> chapterList = new ArrayList<String>();
    FileInputStream fileInputStream = new FileInputStream(novel);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,getCharsetOfNovel(novel));
BufferedReader novelbr = new BufferedReader(inputStreamReader);
int currentIndex = 1;
String line = novelbr.readLine();
while(line != null) {
if(line.indexOf("第") == 0 && line.indexOf("节") != -1) {
chapterList.add("第" + currentIndex + "章" + line.substring(line.indexOf("节")+1));
currentIndex ++;
} else if (line.indexOf("第") == 0 && line.indexOf("章") != -1) {
chapterList.add("第" + currentIndex + "章" + line.substring(line.indexOf("章")+1));
currentIndex ++;
}
line = novelbr.readLine();
}
novelbr.close();
fileInputStream.close();
return chapterList;
    }
    private static void generateChapterMenuHtmlFile(String folderName,List<String> chapterList) throws Exception {
    String menuPath = folderName+"\\章节目录.html";
    StringBuilder pageContent = new StringBuilder();
    pageContent.append("<html><head>"
                +"<meta http-equiv='content-type' content='text/html;charset=utf-8'>"
                +"<title>"+folderName.substring(folderName.lastIndexOf("\\")+1)+"章节目录</title>"
                +"<head>"
                +"<body bgcolor='#e6f3ff' id='body'>"
                + "<h1 align='center'>章节目录</h1><br>"
                + "<table style='margin :auto;'  cellpadding='10px' cellspacing='0' align='center' border='1'>");
    for (int i = 0; i < chapterList.size(); i++) {
    if(i == 0) {
    pageContent.append("<tr>");
    } else if(i % 5 == 0) {
    pageContent.append("<td><a href='"+chapterList.get(i)+".html'>"+chapterList.get(i)+"</a></td>");
    pageContent.append("</tr>");
    }
pageContent.append("<td><a href='"+chapterList.get(i)+".html'>"+chapterList.get(i)+"</a></td>");
}
    pageContent.append("</table></body></html>");
    PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter(menuPath)));
        out.print(pageContent.toString());
        out.flush();
        out.close();
    }
    /**
     * 判断TXT文件编码方式
     * @param fileName
     * @return
     * @throws IOException
     */
    private static String getCharsetOfNovel(File novel) throws IOException {  
    BufferedInputStream bin = new BufferedInputStream(new FileInputStream(novel));  
         byte[] head = new byte[3];  
         bin.read(head, 0, head.length);
         String encoding = "gb2312";    
         if (head[0] == -1 && head[1] == -2 )    
        encoding = "UTF-16";    
         if (head[0] == -2 && head[1] == -1 )    
        encoding = "Unicode";    
         if(head[0]==-17 && head[1]==-69 && head[2] ==-65)    
        encoding = "UTF-8";       
         return encoding;   
    } 
    public static void generate(File novel) throws Exception {
    String folderName = genarateFolder(novel);
    if(folderName == null) {
    return ;
    }
    List<String> chapterList = getChapterList(novel);
    generateChapterMenuHtmlFile(folderName, chapterList);
    FileInputStream fileInputStream = new FileInputStream(novel);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,getCharsetOfNovel(novel));
BufferedReader novelbr = new BufferedReader(inputStreamReader);
int currentPageIndex = -1;
StringBuilder content = new StringBuilder();
String line = novelbr.readLine();
while(line != null) {
if(line.indexOf("第") == 0 && (line.indexOf("节") != -1 || line.indexOf("章") != -1)) {
if(currentPageIndex > -1) {
generateChapterHtmlFile(currentPageIndex, content.toString(),chapterList,folderName);
content.delete(0, content.length());
}
currentPageIndex ++;
} else if(currentPageIndex > -1) {
content.append(line+"<br><br>");
}
line = novelbr.readLine();
}
novelbr.close();
fileInputStream.close();
    }
    public static void main(String[] args) throws Exception {
File folder = new File("F:\\小说");
File[] files = folder.listFiles();
for (int i = 0; i < files.length; i++) {
Separater.generate(files[i]);
}
}

}


      所有小说的TXT文件都下载在“F:\小说”文件夹里,我把这个程序打包成一个jar包也放在这个文件夹里,每次下载后只要执行一次就好,已经生成处理过的小说会直接跳过。

写程序的时候也遇到了一些问题

1.小说文件编码格式不统一,有些是utf-8,有些是gb2312,查了之后发现只要通过判断前几个字节可以知道文件编码,gb2312前几个字节没有规律,无bom的utf8也不能判断,还好windows下默认有bom。

2.打包之后发现执行后生成的html中文乱码,百度了一下是因为Java虚拟机执行后默认编码为gbk,命令行执行时加Dfile.encoding=UTF-8可以解决,我直接添加系统环境变量,变量名为: JAVA_TOOL_OPTIONS, 变量值为:-Dfile.encoding=UTF-8。

  • 8
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用C#中的System.IO和System.Text命名空间来实现小说txt章节的功能。 以下是一个简单的示例代码,可以将输入的小说txt文件按照章节为多个单独的txt文件,并按照章节命名: ```csharp using System; using System.IO; using System.Text; namespace NovelSplitter { class Program { static void Main(string[] args) { // 输入小说txt文件路径 Console.Write("请输入小说txt文件路径:"); string filePath = Console.ReadLine(); // 读取小说txt文件内容 string novelText = File.ReadAllText(filePath, Encoding.UTF8); // 按章节并保存为单独的txt文件 string[] chapters = novelText.Split(new string[] { "第" }, StringSplitOptions.RemoveEmptyEntries); for (int i = 1; i < chapters.Length; i++) { string chapterText = chapters[i]; int endIndex = chapterText.IndexOf("章"); string chapterTitle = "第" + chapterText.Substring(0, endIndex) + "章"; chapterText = chapterText.Substring(endIndex + 1); // 将章节文本保存到单独的txt文件中 string chapterFilePath = Path.Combine(Path.GetDirectoryName(filePath), chapterTitle + ".txt"); File.WriteAllText(chapterFilePath, chapterText, Encoding.UTF8); } Console.WriteLine("小说已按章节并保存为单独的txt文件。"); Console.ReadLine(); } } } ``` 使用方法: 1. 将上述代码保存为NovelSplitter.cs文件; 2. 使用Visual Studio或其他C#编译器编译NovelSplitter.cs文件,生成可执行文件NovelSplitter.exe; 3. 打开命令行终端,进入NovelSplitter.exe所在目录; 4. 运行NovelSplitter.exe,按照提示输入小说txt文件路径; 5. 程序将会按照章节小说txt文件,并将各章节保存为单独的txt文件,保存在原小说txt文件所在目录中。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值