写一个方法传入一个File对象file和一个字符串str参数,统计这个字符串在这个文件中出现的次数



import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class four {
    public static void main(String[] args) throws IOException {
        four aa = new four();
        //aa.selectCountInfile("d:\\out.txt","a");
        System.out.println(aa.selectCountInfile("d:\\out.txt","a"));
    }

    /**
     * 写入一个方法,输入一个文件名和一个字符串,统计这个字符串在这个文件中出现的次数。
     * @param fileName 文件
     * @param str 查找的字符串
     * @return
     * @throws Exception
     */
    public int selectCountInfile(String filename,String str) throws IOException {

        BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(filename)));

        StringBuilder readLine=new StringBuilder();
        String line;
        /**
         * BufferedReader的readLine()方法用来读一行文字, 一行被视为由换行符('\ n'),回车符('\ r')中的任何一个或随后的换行符终止
         */
        while((line=br.readLine())!=null) {
            readLine.append(line);//把读到的一行文字追加到StringBuilder字符串中
        }
        int index;int count = 0;
        /**
         * StringBuilder的indexOf(string类型)方法:返回指定子字符串第一次出现的字符串内的索引
         * 如果字符串参数作为该对象中的子字符串发生,则返回第一个这样的子字符串的第一个字符的索引; 如果它不作为子串发生,则返回-1
         */
        while ((index=readLine.indexOf(str))!=-1) {
            /**
             * 删除此序列的子字符串中的字符
             */
            readLine.delete(0, index+str.length());
            count++;
        }
        return count;

    }
}

输出为:

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值