今天晚上我发现我有一个毛病 总喜欢看自己的博客访问量。。。
看着一点一点的增加 就有一种学习,写博客的动力
记得以前自己记录下来时间 然后记录下访问量 ...想想好幼稚
既然想成为一个程序员 当然要方便自己了~
所以就写了一个小程序
开始了
既然要读取你的博客访问量 找到你csdn的随便一篇文章 或者主页。(比如我的:http://blog.csdn.net/su20145104009?viewmode=contents)
URL url = new URL("http://blog.csdn.net/su20145104009?viewmode=contents");
而为了csdn服务器端禁止抓取,那么这个你可以通过设置User-Agent来欺骗服务器.
connection = url.openConnection();
//User-Agent来欺骗服务器. 避免出现错误代码403
connection.setRequestProperty("User-Agent",Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
开始通信了~
connection.connect();
下面 ,需要读取网页的内容 ,肯定要用到"工具"
InputStream is = null;
//字符流
InputStreamReader isr = null;
//缓冲流
BufferedReader br = null;
//网页编码
String context = null;
读取内容
//获得网页的字节输入流
is = connection.getInputStream();
//将字节输入流转换为字符输入流 并设置转码格式为utf-8
isr = new InputStreamReader(is, "utf-8");
//将字符流转换为缓冲流
br = new BufferedReader(isr);
然后就是读取存在缓冲流的内容,保存在context
//一行一行读取网页内容
context = br.readLine();
while (br.readLine() != null) {
context += br.readLine();
}
context里面是网页的源码 ,内容那么多 怎么得到我们想要的信息呢? 是的,正则表达式 不懂得给你分享个视频
//通过正则表达式 获得访问人气那一行html代码
private static void deal(String context) {
String regex = "<li>访问:<span>.{1,10}次</span></li>";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(context);
if (m.find()) {
//m.group(0)为匹配到的内容 通过getCount方法处理得到访问数量
int count = getCount(m.group(0));
//写入到文本内容
write(count);
}
}
得到当前访问量count 剩下就是写入到文本。不过我还特意加了一个功能 首先读取上一次的访问量 求差 增加了多少~
由于我文件的是保存到桌面 所以首先获得桌面路径
File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
String desktopPath = desktopDir.getAbsolutePath();
然后设置文件的路径
File file = new File(desktopPath + "/blogView.txt");
如果文件不存在 就新建
if (!file.exists()) {
file.createNewFile();
}
如果存在 就是用bufferedReader读取信息
br = new BufferedReader(new FileReader(file));
由于一次只能读取一行 ,而我们要获得的是文件中最后一次的访问量 所以需要一个中间变量
具体如下:
String preBlogView = null;
//中间变量
String temp = null;
while ((temp = br.readLine()) != null) {
preBlogView = temp;
}
然后使用getCount处理得到的信息,返回上次的访问量
//得到上次访问人气
int preCount = getCount(preBlogView);
然后就是写入了~
不再说
<span style="white-space:pre"> </span> // 获得当前日期
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd hh:mm:ss a");
writeContext += "当前访问量:" + count + "人\t";
writeContext += sdf.format(date) + "\t";
writeContext += "增加了" + (count - preCount) + "人";
bw.write(writeContext);
//换行
bw.newLine();
似乎每次我们都要打开eclipse运行 挺麻烦的 。所以 用bat脚本 运行cmd命令 直接把bat脚本放到桌面 双击就可以啦
首先把我们的class文件复制一份 一定要把里面的包名删除哦 不然运行报错的
我把class文件放到了E盘 使用javac编译 java运行
bat命令
运行效果
双击bat脚本就能看到访问数量 如何呀 ~~