JAVA通过epublib解析EPUB格式的电⼦书
什么是 epub 格式
就像视频⽂件有 MP4,AVI,RMVB 等等⼀样!电⼦书也有很多种格式:
可以将 epub 格式的电⼦书更换后缀名,然后解压打开查看⾥⾯的⽂件信息。
Java 解析 Epub 格式电⼦书
刚接到这个需求的时候,在⽹上了很久,没到很好的解析⽅法,最后到了 epublib 这个解析库,但是下载对应的 jar 很⿇烦,最终在maven 仓库搜索到了。
epublib 解析库
epublib:a Java library for reading and writing epub files (⼀个⽤于读写 epub ⽂件的 Java 库)
第⼀步:引⼊对应的 pom ⽂件
<dependency>
<groupId>com.positiondev.epublib</groupId>
<artifactId>epublib-core</artifactId>
<version>3.1</version>
</dependency>
<!--html解析 -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.12.1</version>
</dependency>
第⼆步:常⽤关键类
1.Book      表⽰电⼦书。通过 book 对象可以获取 resource,Metadata 等具体内容
2.Resource  表⽰电⼦书内容资源,⼀个 Resource 就是电⼦书的⼀部分内容,这资源信息可以是 html,css,js,图⽚等;
3.Resources  表⽰电⼦书全部的 Resource 对象。可以⽤过 id,herf,MediaType 来获取对应的 Resource 对象
4.MetaData  表⽰电⼦书的开篇信息。⽐如,作者,出版社,语⾔等;
5.Spine  电⼦书的 resource 顺序,有⼈说是⽬录信息,其实不是,是 resource 的阅读顺序,是线性结构的
6.TableOfContent 电⼦书的⽬录信息,是树形结构的。可以获取到⽬录对应的resource。
7.MediaType  Resource 的类型描述。⽤于说明此 Resource 是何种类型(CSS/JS/图⽚/HTML/ VEDIO 等)。
第三步:解析⼀个epub⽂件
public static void main(String[] args) {
File file = new File("E:\\Download\\红楼梦.epub");
InputStream in = null;
try {
//从输⼊流当中读取epub格式⽂件
EpubReader reader = new EpubReader();
in = new FileInputStream(file);
Book book = adEpub(in);
//获取到书本的头部信息
Metadata metadata = Metadata();
System.out.println("FirstTitle为:"+FirstTitle());
//获取到书本的全部资源
Resources resources = Resources();
System.out.println("所有资源数量为:"+resources.size());
//获取所有的资源数据
Collection<String> allHrefs = AllHrefs();
for (String href : allHrefs) {
Resource resource = ByHref(href);
//data就是资源的内容数据,可能是css,html,图⽚等等
byte[] data = Data();
// 获取到内容的类型  css,html,还是图⽚
MediaType mediaType = MediaType();
}
//获取到书本的内容资源
List<Resource> contents = Contents();
System.out.println("内容资源数量为:"+contents.size());
//获取到书本的spine资源线性排序
Spine spine = Spine();
System.out.println("spine资源数量为:"+spine.size());
//通过spine获取所有的数据
List<SpineReference> spineReferences = SpineReferences();
for (SpineReference spineReference : spineReferences) {
Resource resource = Resource();
//data就是资源的内容数据,可能是css,html,图⽚等等
byte[] data = Data();
/
/ 获取到内容的类型  css,html,还是图⽚
MediaType mediaType = MediaType();
}
//获取到书本的⽬录资源
TableOfContents tableOfContents = TableOfContents();
System.out.println("⽬录资源数量为:"+tableOfContents.size());
//获取到⽬录对应的资源数据
List<TOCReference> tocReferences = TocReferences();
for (TOCReference tocReference : tocReferences) {
Resource resource = Resource();
//data就是资源的内容数据,可能是css,html,图⽚等等
byte[] data = Data();
// 获取到内容的类型  css,html,还是图⽚
MediaType mediaType = MediaType();
Children().size()>0){
//获取⼦⽬录的内容
}
}
} catch (Exception e) {
reference group
e.printStackTrace();
} finally {
//⼀定要关闭资源
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意事项
1 解析后得到的data内容数据是html格式的富⽂本内容,如果需要纯⽂本,可以通过jsoup获取P标签的⽂本内容就可以了,但是获取后的纯⽂本排版就会乱。
2 资源当中可能会存在图⽚和css等等,不在⽬录或者spine当中的内容,可以通过ByHref等⽅法获取。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。