Java完成一個小說收集法式的簡略實例。本站提示廣大學習愛好者:(Java完成一個小說收集法式的簡略實例)文章只能為提供參考,不一定能成為您想要的結果。以下是Java完成一個小說收集法式的簡略實例正文
被題目吸引出去的不要罵我。
只是一個簡略的完成,順手寫了來下載一部愛好的小說的。示例中的小說只是示例,不是我的菜。
應用了jsoup。挺好用的一個對象。
有須要的話,參考下本身改吧。挺簡略的,是吧。
代碼以下:
package com.zhyea.doggie;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class Doggie {
public static void main(String[] args){
try{
File txtFile = new File("D:/無窮崩壞.txt");
createTxtDoc(txtFile);
addContent(txtFile);
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 向小說文件中添加內容
* @param txtFile
* 小說文件
* @throws IOException
* @throws InterruptedException
*/
private static void addContent(File txtFile) throws IOException, InterruptedException{
appendTxt(txtFile, getBookInfo("無窮崩壞", "啪啪啪狂魔"));
String url = "http://www.83kxs.com/View/12/12653/{pattern}.html";
for(int i=5850686; i<=5945501; i++){
try{
String tmp = url.replace("{pattern}", i+"");
appendTxt(txtFile, getPageContent(tmp));
}catch(Exception e){
e.printStackTrace();
continue;
}
}
}
/**
* 設置書名和作者
* @param bookName
* 書名
* @param author
* 作者
* @return
*/
private static String getBookInfo(String bookName, String author){
return COMMON.replace("{book}", bookName).replace("{author}", author);
}
/**
* 讀取頁面內容
* @param url
* 拜訪途徑
* @return
* @throws IOException
*/
private static String getPageContent(String url) throws IOException{
String rtn = null;
Document doc = Jsoup.connect(url).get();
Elements content = doc.select(".text p");
Elements title = doc.select("#title");
System.out.println(title.text());
content.select("font").remove();
content.select("script").remove();
content.select("ins").remove();
content.select("a").remove();
rtn = title.text() + NEWLINE
+ content.html().replaceAll("<p>", "")
.replaceAll("</p>", "")
.replaceAll("\\<!--(.+)--\\>", "")
.replaceAll(" ", "")
.replaceAll("<br>", NEWLINE)
+ NEWLINE;
return rtn;
}
/**
* 創立新的txt文件
* @param fullName
* 文件全名
* @return
* @throws Exception
*/
private static boolean createTxtDoc(File txtFile) throws Exception{
try{
return txtFile.createNewFile();
}catch(Exception e){
throw e;
}
}
/**
* 向txt文件中追加內容
* @param txtFile
* 要操作的txt文件
* @param content
* 要追加的內容
* @throws IOException
*/
private static void appendTxt(File txtFile, String content) throws IOException{
FileWriter writer = null;
try{
writer = new FileWriter(txtFile, true);
writer.append(content);
}finally{
if(null!=writer)writer.close();
}
}
/**
* 換行符
*/
static final String NEWLINE = System.getProperty("line.separator");
/**
* 書前的通用信息
*/
static String COMMON = "------------------------------------------------------------------" + NEWLINE
+ "--------------- 書名:{book}" + NEWLINE
+ "--------------- 作者:{author}" + NEWLINE
+ "--------------- zhyea.com" + NEWLINE
+ "------------------------------------------------------------------" + NEWLINE;
}
以上就是小編為年夜家帶來的Java完成一個小說收集法式的簡略實例全體內容了,願望年夜家多多支撐~