java - 带有 printwirter 参加方法的循环仅写入最后搜索的单词
问题描述
尽管使用了参加方法,Printwriter 仅将带有搜索词的最后一行写入文件,而不是每行带有搜索词的每一行。我认为我的代码有问题。任何人都可以检查代码并帮助我吗?
package JanKozak6;
import java.util.Scanner;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner scan1 = new Scanner(System.in);
//System.out.println("Write a name of a File.txt you want to check in project home directory");
//String nameOfFile = scan1.nextLine();
try {
FileReader read1 = new FileReader("FileToRead");
BufferedReader read11 = new BufferedReader(read1);
System.out.println("Give a word to find in text lines");
String wordToFind = scan1.nextLine();
System.out.println("wordToFind: " + wordToFind);
if (read11.readLine() != null) {
String FoundWord = read11.readLine();
System.out.println("Read the line");
while (FoundWord.contains(wordToFind)) {
try {
System.out.println("Try to write");
FileWriter write1 = new FileWriter("FoundWords", true);
PrintWriter write11 = new PrintWriter(write1);
System.out.println("Writing...");
//write11.write(FoundWord);
write11.append(FoundWord);
System.out.println("Closing BuffereWriter");
write11.close();
}
catch (IOException ex) {
System.out.println("FoundWord have not been written");
}
}
}
read11.close();
}
catch (IOException ex)
{
System.out.println("Exception: The file is not found");
}
}
}
解决方案
您没有循环读取文件。试试这个:
public static void main(String[] args) {
Scanner scan1 = new Scanner(System.in);
//System.out.println("Write a name of a File.txt you want to check in project home directory");
//String nameOfFile = scan1.nextLine();
try {
FileReader read1 = new FileReader("FileToRead");
BufferedReader read11 = new BufferedReader(read1);
System.out.println("Give a word to find in text lines");
String wordToFind = scan1.nextLine();
String FoundWord=null;
System.out.println("wordToFind: " + wordToFind);
while((FoundWord=read11.readLine()) != null) {
System.out.println("Read the line");
if(FoundWord.contains(wordToFind)) {
try {
System.out.println("Try to write");
FileWriter write1 = new FileWriter("FoundWords", true);
PrintWriter write11 = new PrintWriter(write1);
System.out.println("Writing...");
//write11.write(FoundWord);
write11.append(FoundWord);
System.out.println("Closing BuffereWriter");
write11.close();
}
catch (IOException ex) {
System.out.println("FoundWord have not been written");
}
}
}
read11.close();
}
catch (IOException ex)
{
System.out.println("Exception: The file is not found");
}
}
}
推荐阅读
- postgresql - 解析服务器运行 postgres 解析错误:错误:列“_rperm”不存在
- java - 如何获取文件的创建时间并将其放入数组中?
- python - 如何确保输入数字会得到所列的随机结果?
- r - 引用同名的列表对象
- rss - Overcast 和 Podcast addict 等应用程序如何检索播客列表?
- dafny - Dafny - 检查数组值是否唯一,但嵌套的 forall 存在不由循环维护
- proxy - 关于 CoAP 客户端代理功能
- c++ - 如何初始化另一个类的数组的静态常量成员,并使用它?
- angular - Angular Firebase Guards,阻止具有特定角色的路由
- r - 如何通过 R 抓取超链接并在输出文件中保持超链接可点击?