search String查找字符串

package jdbc;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class SearchString {
    
    private static int mount = 0;

    public static void main(String[] args) {
        String fileName = "d:/text";
        File file = new File(fileName);
        args = new String[]{"pw"};
        for (int i = 0; i < args.length; i++){
            findFile(file, args[i]);
            print(args[i]);
        }
    }

    private static void findFile(File file, String word) {
        File[] files = file.listFiles();
        for(int i = 0; i < files.length; i++){
            if(files[i].isDirectory()){
                findFile(files[i], word);
            }else {
                search(files[i], word);
            }
        }
    }

    private static void search(File file, String word) {
        int j = 0, k = 0, ch = 0;
        String str = null;
        try {
            FileReader in = new FileReader(file);
            while ((ch = in.read()) != -1){
                str += (char)ch;
            }
            if(str != null){
                while (str.indexOf(word, j) != -1){
                    k++;
                    j = str.indexOf(word, j) + 1;
                }
            }
            if(k > 0){
                System.out.println(file.getAbsolutePath() + k);
                mount++;
            }
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void print(String word) {
        if(mount != 0){
            System.out.println(mount + word);
            mount = 0;
        }else {
            System.out.println("");
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值