用java编写一个程序,统计一个文件中的字符数、单词数以及行数。单词由空格符分隔,文件名应该作为命令行参数被传递
时间: 2024-02-17 09:02:20 浏览: 38
好的,这是一个简单的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+` 来分隔单词,这意味着单词可以由一个或多个空格符分隔。最后,它输出统计结果。