用java编写一个程序,统计一个文件中的字符数、单词数以及行数。单词由空格符分隔,文件名应该作为命令行参数被传递
时间: 2024-02-17 14:02:20 浏览: 121
![ZIP](https://csdnimg.cn/release/download/static_files/pc/images/minetype/ZIP.png)
基于Python实现的一个命令行文本计数统计程序,可统计纯英文txt文本中的字符数,单词数,句子数,Python文件行数
好的,这是一个简单的Java程序,可以完成你的需求:
```java
import java.io.*;
public class FileStats {
public static void main(String[] args) {
if(args.length == 0) {
System.out.println("Please provide the filename as a command line argument");
return;
}
String filename = args[0];
int charCount = 0;
int wordCount = 0;
int lineCount = 0;
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
while((line = reader.readLine()) != null) {
lineCount++;
charCount += line.length();
String[] words = line.split("\\s+");
wordCount += words.length;
}
reader.close();
} catch(IOException e) {
System.out.println("An error occurred while reading the file");
e.printStackTrace();
}
System.out.println("Character count: " + charCount);
System.out.println("Word count: " + wordCount);
System.out.println("Line count: " + lineCount);
}
}
```
这个程序首先检查是否有文件名作为命令行参数传递,如果没有则提示用户提供文件名。然后,它使用 `BufferedReader` 读取文件中的每一行,计算字符数、单词数和行数。注意,它使用正则表达式 `\\s+` 来分隔单词,这意味着单词可以由一个或多个空格符分隔。最后,它输出统计结果。
阅读全文
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)