最近一直在手机上看小说,于是想能不能在电脑上看,在网上查了一下资料,主要参考这一篇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。

TXT格式小说实现分章节相关推荐

  1. 论文撰写格式-------Mathtype公式分章节自动编号及引用编号

    又到了一年一度的毕业季,一个头两个大,毕设论文好不容易接近尾声了,迎来了撰写的必经之路---- ­­­­­­­­修改格式.仅以此文稍作记录,预祝正在阅读本文的同学们和我毕业顺利,一起走花路! 论文撰写 ...

  2. 用python爬取笔趣阁小说并分章节保存到本地

    在宿舍无聊时想做点小程序,刚好又看到笔趣阁的广告,就想着爬一下小说看看,通过网上的爬取教程整理的 使用beautifulsoup解析request获取的HTML http://beautifulsou ...

  3. 用txt阅读器按目录分章节阅读小说

    用txt阅读器按目录分章节阅读小说 最近,我从网上下载了一部名为<大主宰>的长篇玄幻小说.这是一部章回小说,截至目前,已写到第1330章,真可谓宏篇巨制.我想用一个分章节的文本阅读器阅读它 ...

  4. 【githubshare】支持有声小说与文本小说,可下载 mobi、epub、txt 格式文本小说,兼容 Win

    分享一款项目管理后台搭建工具:Motor Admin.无需编码,即可快速为应用搭建简单易用的管理后台. 开发者可定制 CRUD 界面,并提供表单生成器.SQL 语句在线运行.数据可视化.应用管理面板. ...

  5. python对txt分段处理_使用python对txt格式的小说进行处理

    vim的确是神器,可惜sed与vim不完全通用.这篇文章受< 用vim对txt格式的小说重新排版>的启发,在此致谢! 经常下载txt的电子书,格式却不合心意,只好自己再处理.首要的就是处理 ...

  6. Pythont打开 txt 格式的文件

    一.Pythont如何打开 txt 格式的文件? 1.首先我使用pycharm创建一个项目,然后在这个项目里面再创建一个python的包,然后在里面创建一个demo1.txt的文件吗,里面写一些我看过 ...

  7. 有哪些能支持epub、txt格式的电子书阅读器?能在安卓手机上用的?

    在手机上看书有许多方便之处,随着智能手机的硬件功能越来越发达,无论大学生还是工作族每天与手机端网络资源相接触已经成为了我们生活的常态.可是不得不说手机端打开资源的方式又常常会令我们头痛,那么如何能够又 ...

  8. 如何将xml格式转换为yolov5所需的txt格式

    如今,深度学习非常热门,制作数据集是深度学习很重要的一环.制作数据集就离不开打标签,我们打出来的标签可能是 txt 格式 或者 xml 格式 或者json格式,但是yolo运行的标签格式是txt格式 ...

  9. mysqlOracle导入导出txt格式的数据

     一: mysql导入数据load data infile用法 导出一张表的数据,以',' 为分隔符 select * from pet  into  outfile 'c:/pet.txt'   ...

最新文章

  1. 什么是标记符控制的分水岭算法
  2. Android7.1update.zip升级在system/bin下新增可执行文件没有可执行权限问题
  3. inotifywait监听php,利用inotifywait监控主机文件和目录
  4. 无服务器-构建现代应用程序的新方法
  5. 什么是python函数_什么是python函数
  6. 自动驾驶模拟器Carla之python编程-(1)简介
  7. 约会软件上的小姐姐,其实是StyleGAN生成的假人
  8. 中国移民去哪儿 新京报
  9. python `__str__`
  10. ROS入门-12.服务端Server的编程实现
  11. window安装python报错_win10下Python安装pycrypto报错
  12. c语言中static 用法
  13. 摄影测量学——航摄像片的内、外方位元素和像点空间直角坐标变换与中心投影构像方程
  14. python把文件中的邮箱分类 保存到相应的文件里面
  15. Receive 163 mails
  16. 副业宝典~副业思维让你拥有更多钱
  17. 自己做量化交易软件(42)小白量化实战15--自编股票软件公式历史与聚宽量化平台仿大智慧指标回测设计
  18. Markdown编辑器——Editor.md的使用
  19. 墨菲定律吉德林法则吉尔伯特定律沃尔森法则福克兰定律
  20. 迅歌KTV服务器各型号,2017年ktv必点歌曲排行榜

热门文章

  1. 域名命名规则及交易平台
  2. JavaScript 模块化介绍
  3. 计算机ppt制作培训心得,中小学电脑制作活动培训心得体会范文
  4. 不用穿越,也能体验百年前的老北京,这个AI修复视频火爆全网
  5. Unity如何改变和调整粒子系统大小和程序入门,非美术向
  6. linux系统下替换图片,GIMP 图像处理软件如何更换图片背景色
  7. STM32之视频播放器(AVIJPEG)
  8. 面试中软件开发测试题--Java自学网
  9. 中望cad2017专业版|中望cad2017sp专业版下载
  10. python画二维温度云图_python定制后处理云图