Java 资料操作与过滤器
Java 文件操作与过滤器
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; }