您的位置:首页 > 编程语言 > Java开发

读取txt文件统计文章里"java"字符串出现的次数

2014-05-16 17:36 537 查看
//看网上读取文件和统计字符出现的次数多是单独的案例,于是随手整合一个


//作者:Divd.Liu QQ:475731259 Email:beijing2008lxd@hotmail.com

//整合参考的资源有:

(01)马如林的博客:/article/2837284.html

(02)还有一个百度里的资源不知道是谁的贡献^_^。

import java.io.BufferedReader;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

/**

* 读取一txt文档,每次读取一行,用BufferedReader(FileReader fr)

*

* */

public class Demo12 {

public static void main(String[] args) throws IOException {

File f = new File("D:/date.txt");

FileReader fr = new FileReader(f);

BufferedReader br = new BufferedReader(fr);

String str;

int totalCount = 0;

String key = "java";

while ((str = br.readLine()) != null) {

totalCount += countKey(str, key);

}

System.out.println("文章中一共出现了:" + key + ":" + totalCount + "次");

}

//

public static int countKey(String str, String key) {

int index = 0;

int count = 0;

while ((index = str.indexOf(key, index)) != -1) {

index += key.length();

// 或//str=str.subString(index+key.length());//从指定位置向后截取字符串

count++;

}

return count;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐