Java 统计文件ip_统计nginx访问日志中ip前24位的访问次数,java

nginx服务器的access.log日志中,统计访客ip的访问次数。

我这个版本只统计前24位的数据。

还不如在linux用shell来统计,java写出来的代码太多了。

package file;

import java.io.*;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.*;

/**

* 统计nginx访问日志中ip前24位的访问次数

* @author zhl

* @date 2019/10/29 0029 14:03

*/

public class ReadFile {

static SimpleDateFormat format = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss z",Locale.ENGLISH);

static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

/**

* 开始时间

*/

static String start_date ="2019-11-1 00:00:00";

/**

* 结束时间

*/

static String end_date = "2019-11-6 23:59:59";

/**

* 文件路径

*/

static String file_path = "C:\\Users\\zhuho\\Documents\\access.log";

public static void main(String[] args) throws IOException, ParseException {

FileReader fr = new FileReader(file_path);

BufferedReader br = new BufferedReader(fr);

String tempString;

int i =0;

TreeMap map = new TreeMap<>();

while( (tempString = br.readLine()) != null){

//System.out.println(tempString);

if(tempString.matches("(.*)spider(.*)")){

//System.out.println("爬虫 continue;");

continue;

}

Date this_date ;

{

//识别日期

int date_start_index = tempString.indexOf("[");

int date_end_index = tempString.indexOf("]");

String date_string = tempString.substring(date_start_index+1, date_end_index);

this_date = format.parse(date_string);

}

//只处理在指定日期范围内的数据

if(this_date.after(df.parse(start_date)) && this_date.before(df.parse(end_date))){

/**

* 111.111.111.*

* ip前24位的最大长度是12个字符

*/

tempString = tempString.substring(0,12);

int index = tempString.lastIndexOf(".");

tempString = tempString.substring(0,index);

if(map.get(tempString) == null){

map.put(tempString, 1);

}else{

map.put(tempString, map.get(tempString)+1);

}

}

/*if(i>1000){

return;

}

i++;*/

}

fr.close();

//把treemap转换为list集合利用sort排序

List> list=new ArrayList>(map.entrySet());

Collections.sort(list,new Comparator>() {

@Override

public int compare(Map.Entry o1, Map.Entry o2) {

return o2.getValue()-o1.getValue();//倒序

}

});

System.out.println("查询范围:");

System.out.println(start_date +"\t"+ end_date);

for (Map.Entry entry : list) {

System.out.println(entry.getKey()+"\t"+entry.getValue());

}

}

}

输出:

查询范围:

2019-11-1 00:00:002019-11-6 23:59:59

14.215.1762932

223.104.31536

117.136.381303

39.156.651242

124.64.16370

112.34.110323

36.102.228290

124.64.18273

219.143.154254

36.110.199251

111.206.36220

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值