zoukankan      html  css  js  c++  java
  • 在一个文件中,读取很多个txt文件,并根据关键字显示其内容

    我这里搜索的市一个G盘下的test文件夹

    package one;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    
    public class testIO {
    	public static void readTestFile(String testFile,String key){
    		try {
    		String encoding="GBK";
    		File file =	new File(testFile);
    		if(file.isFile()&&file.exists()){
    			InputStreamReader read = new InputStreamReader(new FileInputStream(file),encoding);
    			BufferedReader bufferedReader = new BufferedReader(read);
    			String lineTet = null;
    			int num=0;
    			while((lineTet=bufferedReader.readLine())!=null){
    				if(lineTet.indexOf(key)==0){
    					System.out.println(lineTet);
    				}
    				
    			}
    			read.close();
    		}else{
    			System.out.println("找不到指定文件");
    		}
    		
    		} catch (UnsupportedEncodingException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			} catch (FileNotFoundException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			} catch (IOException e) {
    				System.out.println("读取错误啊");
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		
    	}
    	
    }
    

      然后直接创建测试类测试里面是否能完成

    package one;
    
    import java.io.File;
    
    public class test {
    	@SuppressWarnings("static-access")
    	public static void main(String[] args) {
    		File fileDir =new File("G:\test");
    		File[] testFile = fileDir.listFiles();
    		testIO ti = new testIO();
    		String key="ip";
    		if(testFile.length>0){
    		for(int i=0;i<testFile.length;i++){
    			if(testFile[i].isFile()&&testFile[i].getName().endsWith(".txt")){
    				ti.readTestFile(testFile[i].getAbsolutePath(), key);
    			}
    		}
    		System.out.println(testFile.length);
    	}else{
    		System.out.println("这个文件夹中没有txt文件");
    	}
    	}
    }
    

      

    面先判断出这个文件夹有多少个txt的文件,把有的都显示出来,在进行下一步的判断,让有的在进行关键字搜索,关键字是ip,然后在显示出来

  • 相关阅读:
    Spring Boot 之Profile
    Spring Security初识
    Github使用进阶
    数据库JDBC
    Java内存模型(JMM)的可见性
    Spring Boot 整合Spring Data JPA
    Git版本控制工具初识
    Linux美化——终端提示符
    Python's Exception 层级结构
    试写Python内建函数range()
  • 原文地址:https://www.cnblogs.com/jummy/p/7161699.html
Copyright © 2011-2022 走看看