今天晚上我发现我有一个毛病 总喜欢看自己的博客访问量。。。
看着一点一点的增加 就有一种学习,写博客的动力
记得以前自己记录下来时间 然后记录下访问量 ...想想好幼稚
既然想成为一个程序员 当然要方便自己了~
所以就写了一个小程序
开始了
既然要读取你的博客访问量 找到你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(); }
//通过正则表达式 获得访问人气那一行html代码 private static void deal(String context) { String regex = "
得到当前访问量count 剩下就是写入到文本。不过我还特意加了一个功能 首先读取上一次的访问量 求差 增加了多少~
由于我文件的是保存到桌面 所以首先获得桌面路径
File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory(); String desktopPath = desktopDir.getAbsolutePath();
File file = new File(desktopPath + "/blogView.txt");
if (!file.exists()) { file.createNewFile(); }
br = new BufferedReader(new FileReader(file));
所以需要一个中间变量
具体如下:
String preBlogView = null; //中间变量 String temp = null; while ((temp = br.readLine()) != null) { preBlogView = temp; }然后使用getCount处理得到的信息,返回上次的访问量
//得到上次访问人气 int preCount = getCount(preBlogView);
不再说
// 获得当前日期
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();