java 文件中查找指定的单词,查找指定文本文件中的单词数的Java程序

查找指定文本文件中的单词数的Java程序

1 说明

在此程序中,我们需要找到给定文本文件中出现次数最多的单词。这可以通过使用文件指针以读取模式打开文件来完成。逐行读取文件。一次分割一行并存储在数组中。遍历数组并计数单词。该程序中使用的data.txt文件的内容如下所示。

data.txt内容如下:

A computer program is a collection of instructions that performs specific task when executed by a computer.

Computer requires programs to function.

Computer program is usually written by a computer programmer in programming language.

A collection of computer programs, libraries, and related data are referred to as software.

Computer programs may be categorized along functional lines, such as application software and system software.

2 算法思路

步骤1:开始

第2步:定义字符串行

步骤3:SET count =0

步骤4:使用File Reader以读取模式打开文件。

步骤5:从文件中读取行

步骤6:重复步骤7至步骤8,直到到达文件末尾

第7步:将行拆分为单词,然后将其存储在数组字符串word []中。

步骤8: count = count + words.length

步骤9:打印count。

步骤10:结束

3 程序实现

/**

* 一点教程网: http://www.yiidian.com

*/

import java.io.BufferedReader;

import java.io.FileReader;

public class CountWordFile

{

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

String line;

int count = 0;

//Opens a file in read mode

FileReader file = new FileReader("data.txt ");

BufferedReader br = new BufferedReader(file);

//Gets each line till end of file is reached

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

//Splits each line into words

String words[] = line.split("");

//Counts each word

count = count + words.length;

}

System.out.println("Number of words present in given file: " + count);

br.close();

}

}

以上代码输出结果为:

Number of words present in given file: 63

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值