很早之前就想把CSDN博客导出到本地来,CSDN上好像有个用C#写的(牛啊),但是我看到的时候已经不能用了,
C#也不太会,我估计用Java应该也能实现,最近想回顾下Java就来试试,希望可以实现个简单的吧。
(如果CSDN有开放API就好了,这些东西就很容易实现了,想想还有点儿小激动呢)
1. 需求分析
我们想用Java将博客导出,大概需要如下几步:(最简单的情况)
1. 让Java访问我们的博客:Java里面可以很方便的实现,后面开发时详述,这里可能有个登录的问题,不登陆应该也可以的
2. 将网页内容保存到本地文件:这个就是IO了,也是不难的,这里的话,有个命名的问题,我们最好可以找到博客的名称,用正则表达式的话,应该可以,
或者其他的一些什么工具可以解析HTML的
3. 将本地文件进行其他格式的转换:这个应该有开源的JAR包之类的可以使用
2. 让Java访问我们的博客
好了,我们先简单实现下看看
/**
* 根据博客URL获取博客内容
*
* @param blogURL
* 博客地址
* @return 字符串博客内容
* @throws IOException
*/
public String fetchBlog(String blogURL) throws IOException {
//我们将博客内容存在字符串中
StringBuffer result = new StringBuffer("");
HttpURLConnection con = null;
BufferedReader br = null;
try {
URL url = new URL(blogURL);
//打开连接
con = (HttpURLConnection) url.openConnection();
//设置 User-agent
con.setRequestProperty("User-agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0");
//判断连接状态
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
//连接成功的话,我们可以获取输出流了
br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String ch = null;
while ((ch = br.readLine()) != null) {
//按行读取
result.append(ch).append("\n");
}
}
} finally {
//关闭流
if (br != null) {
br.close();
br = null;
}
//断开连接
con.disconnect();
}
return result.toString();
}
刚开始的时候,使用HttpURLConnection遇到个错误403,访问被禁止了,可以参考另一篇博客:
Java实例(二) - HttpURLConnection 报403错误
3. 将博客保存到本地
上面的方法,我们将内容存到了字符串中,为了方便,我们改造下上面的方法,我们在按行读取之后,直接就存到文件中
public void fetchBlog(String blogURL) throws IOException {
HttpURLConnection con = null;
BufferedReader br = null;
OutputStream os = null;
BufferedWriter bw = null;
try {
URL url = new URL(blogURL);
//打开连接
con = (HttpURLConnection) url.openConnection();
//设置 User-agent
con.setRequestProperty("User-agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0");
//判断连接状态
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
//输出流
os = new FileOutputStream(new File("E://blog.html"));
bw = new BufferedWriter(new OutputStreamWriter(os));
//连接成功的话,我们可以获取输出流了
br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String ch = null;
while ((ch = br.readLine()) != null) {
bw.write(ch);
bw.write("\n");//换个行
}
}
} finally {
//关闭流
if (br != null) {
br.close();
br = null;
}
if(bw != null) {
bw.flush();
bw.close();
bw = null;
}
if (os != null) {
os.close();
os = null;
}
//断开连接
con.disconnect();
}
}
好了,我们定义个输出流,直接输出到文件中去,但是这里的文件名是我们固定的,不好,我们最好可以找到博客的名字