Java 文件操作与过滤器

本文介绍了一个Java程序,该程序能够批量加载并处理特定格式的日志文件。它使用正则表达式匹配文件名,并通过UTF-8编码读取文件内容。此工具适用于处理带有特定前缀和日期格式的日志文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.InputStreamReader;
import java.util.regex.Pattern;

public class ImportTool
{
	public static void main(String[] args) throws Exception
	{
		ImportTool tool = new ImportTool();

		tool.loadFiles( "data/vehi/", tool.new ImpFilenameFileter( "vehi_[0-9]{8}\\.log" ) );

		int len = tool.files.length;

		for ( int i = 0; i < len; i++ )
		{
			tool.data2table( "tableName", new FileInputStream( tool.files[i] ), "" );
		}
	}


	public void data2table(String tableName, FileInputStream in, String dbConfigFile)
	{
		try
		{
			BufferedReader reader = new BufferedReader( new InputStreamReader( in, "UTF-8" ) );
			try
			{
				String rowData = null;
				while ((rowData = reader.readLine()) != null)
				{
					System.out.println( rowData );

					// do insertData
				}

				System.out.println( "------------------------------------------" );
			}
			finally
			{
				reader.close();
			}

		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

	}


	/**
	 * 从指定目录中加载文件
	 * @author skj
	 */
	public void loadFiles(String basepath, FilenameFilter filter) throws Exception
	{
		File path = new File( basepath );
		if (!path.exists())
		{
			throw new Exception( "目录" + basepath + "不存在!" );
		}

		files = path.listFiles( filter );

	}
	
	/**
	 * 文件过滤器
	 * @author skj
	 */
	public class ImpFilenameFileter implements FilenameFilter
	{
		private Pattern pattern = null;

		public ImpFilenameFileter(String pattern)
		{
			this.pattern = Pattern.compile( pattern );
		}

		@Override
		public boolean accept(File dir, String name)
		{
			return pattern.matcher( name ).matches();
		}
	}

	public File[] files;
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值