根据文件中的内容查找文件

这篇文章描述了一个Java程序,用户输入目录和要查找的文件内容后,遍历目录中的文件,通过读取文件内容并使用StringBuilder和Index方法查找匹配项,以定位含有指定内容的文件并输出其名称和绝对路径。
摘要由CSDN通过智能技术生成

思路:先让用户输入一个目录,然后遍历目录下的所有文件,将文件中的内容提取出来,用StringBuilder将所有字符串拼接,然后再用StringBuilder的Index方法来查找匹配的字符串,从而根据内容找到文件,返回该文件名称以及绝对路径.

源码:

import javax.management.RuntimeErrorException;
import java.io.*;
import java.nio.file.Files;
import java.util.Scanner;

public class IODemo {
    public static void main(String[] args) {
        System.out.println("请输入要查找的目录:");
        Scanner scanner = new Scanner(System.in);
        String directory = scanner.next();
        System.out.println("请输入要查找的文件内容:");
        String content = scanner.next();
        File dire = new File(directory);
        if(!dire.isDirectory()){
            System.out.println("输入目录错误!");
            return;
        }
        scanFile(dire , content);
    }
    private static void scanFile(File dire , String content){
        File[] files = dire.listFiles();
        if(files == null){
            return ;
        }
        for (File file:
             files) {
            if(file.isFile()){
                sreachStr(file , content);
            }else if(file.isDirectory()){
                scanFile(file , content);
            }else{
                ;
            }
        }
    }
    private static void sreachStr(File file , String content) {
        try (InputStream inputStream = new FileInputStream(file)){
            StringBuilder stringBuilder = new StringBuilder();
            while(true){
                byte[] arr = new byte[1024];
                int n = inputStream.read(arr);
                if(n == -1){
                    break;
                }
                String s = new String(arr , 0 , n);
                stringBuilder.append(s);
            }
            if(stringBuilder.indexOf(content) == -1){
            }else{
                String s= file.getAbsolutePath();
                System.out.println("找到文件" + file.getName() +s);
            }
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值