java实现wc函数功能(附完整源码)
时间: 2023-11-28 21:04:16 浏览: 44
以下是Java实现wc函数功能的完整源码:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class WordCount {
public static int countLines(String fileName) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
int lines = 0;
while (reader.readLine() != null) {
lines++;
}
reader.close();
return lines;
}
public static int countWords(String fileName) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
int words = 0;
String line = reader.readLine();
while (line != null) {
String[] parts = line.split("\\s+");
words += parts.length;
line = reader.readLine();
}
reader.close();
return words;
}
public static int countCharacters(String fileName) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
int characters = 0;
int c = reader.read();
while (c != -1) {
characters++;
c = reader.read();
}
reader.close();
return characters;
}
public static void main(String[] args) {
String fileName = "test.txt";
try {
int lines = countLines(fileName);
int words = countWords(fileName);
int characters = countCharacters(fileName);
System.out.println("Lines: " + lines);
System.out.println("Words: " + words);
System.out.println("Characters: " + characters);
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
```
这个程序可以接受一个文件名作为输入,并计算文件中的行数、单词数和字符数。它通过使用BufferedReader读取文件内容,并通过调用Java的String类中的split()方法来计算单词数。最后,它将结果输出到控制台。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)
![](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)