Java设计一程序按行读取文件english.txt内容,并在该行的后面尾加上该英语句子中含有的单词书目,然后再将该行写入到一个名字为englishCountt.txt的文件中。 english.txt内容: The arrow missed the target. They rejected the union demand. Where does this road go to? 输出文件englishCount.txt内容: The arrow missed the target. 句子中单词个数:5 They rejected the union demand. 句子中单词个数:5 Where does this road go to? 句子中单词个数:6
时间: 2024-03-18 13:38:30 浏览: 61
好的,以下是 Java 程序代码,可以实现您所需的功能:
```java
import java.io.*;
public class EnglishCount {
public static void main(String[] args) {
try {
// 打开文件english.txt
File inputFile = new File("english.txt");
FileReader fileReader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// 创建文件englishCount.txt
File outputFile = new File("englishCount.txt");
FileWriter fileWriter = new FileWriter(outputFile);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
// 逐行读取文件english.txt并统计单词数量
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] words = line.split("\\s+");
int wordCount = words.length;
String outputLine = line + " 句子中单词个数:" + wordCount;
bufferedWriter.write(outputLine);
bufferedWriter.newLine();
}
// 关闭文件
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
以上代码会按行读取文件english.txt中的内容,并逐行统计单词数量,在每行的末尾加上单词数量,并将处理后的每行内容写入到一个名为englishCount.txt的文件中。
注意,在Java中,要使用双反斜杠("\\s+")来表示空格符,因为单反斜杠("\s+")会被Java编译器解释为字符串转义符。
阅读全文