遍历文件夹access_log中的所有文件localhost_access_log*.txt,提取IP插入数据库中java代码

时间:2022-11-19 19:57:11

文件夹目录为D:/access_log/:

文件夹中的文件列表如下:

遍历文件夹access_log中的所有文件localhost_access_log*.txt,提取IP插入数据库中java代码

 

每个文件的内容格式如下:

159.226.2.219 - - [10/May/2012:23:13:21 +0800] "POST /dlog/ServiceServlet HTTP/1.1" 203 117
159.226.2.219 - - [10/May/2012:23:13:22 +0800] "POST /dlog/ServiceServlet HTTP/1.1" 200 58
159.226.2.219 - - [10/May/2012:23:13:22 +0800] "POST /dlog/ServiceServlet HTTP/1.1" 200 51
159.226.2.219 - - [10/May/2012:23:13:23 +0800] "POST /dlog/ServiceServlet HTTP/1.1" 200 51
159.226.2.219 - - [10/May/2012:23:13:23 +0800] "POST /dlog/ServiceServlet HTTP/1.1" 200 51
159.226.2.219 - - [10/May/2012:23:13:23 +0800] "POST /dlog/ServiceServlet HTTP/1.1" 200 51
159.226.2.219 - - [10/May/2012:23:13:24 +0800] "POST /dlog/ServiceServlet HTTP/1.1" 200 51
159.226.2.219 - - [10/May/2012:23:13:24 +0800] "POST /dlog/ServiceServlet HTTP/1.1" 200 51
159.226.2.219 - - [10/May/2012:23:13:24 +0800] "POST /dlog/ServiceServlet HTTP/1.1" 200 51
159.226.2.219 - - [10/May/2012:23:13:25 +0800] "POST /dlog/ServiceServlet HTTP/1.1" 200 51
159.226.2.205 - - [10/May/2012:23:13:25 +0800] "GET /dct/scripts/page/pageName.js HTTP/1.1" 200 4532
159.226.2.205 - - [10/May/2012:23:13:25 +0800] "GET /dct/scripts/ajax/ajax.js HTTP/1.1" 200 2431
159.226.2.205 - - [10/May/2012:23:13:25 +0800] "GET /dct/scripts/ajax/comm-manager.js HTTP/1.1" 200 9240
159.226.2.205 - - [10/May/2012:23:13:25 +0800] "GET /dct/scripts/js.js HTTP/1.1" 200 860

 

程序代码如下:

 

package cn.cnic.oms.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import java.sql.Connection;

import cn.cnic.oms.util.Conn;

public class TextTest {

	public static void main(String[] args) {
		Conn.getStmt(Conn.getConn("127.0.0.1", "1521", "orcl", "zhang",
				"xxxx"));
		String sql = "";
		String ip = "";
		try {
			File dir = new File("D:/access_log/");
			File filedir[] = dir.listFiles();
			for (int i = 0; i < filedir.length; i++) {
				String strpath = filedir[i].getAbsolutePath();
				System.out.println(strpath);
				File file = new File(strpath);
				if (file.isFile() && file.exists()) {
					InputStreamReader read = new InputStreamReader(
							new FileInputStream(file));
					BufferedReader bufferedReader = new BufferedReader(read);
					String lineTXT = null;
					while ((lineTXT = bufferedReader.readLine()) != null) {
						ip = lineTXT.split("- -")[0].trim();
						System.out.println(ip);
						sql = "insert into accesslog(ip) values ('" + ip + "')";
						Conn.executeUpdate(sql);
					}
					read.close();
				} else {
					System.out.println("找不到指定的文件!");
				}
			}
			System.out.println("插入完成!");
		} catch (Exception e) {
			System.out.println("读取文件内容操作出错");
			e.printStackTrace();
		}
	}

}