gpt4 book ai didi

java - 使用 printwirter attend 方法的 while 循环仅写入最后搜索的单词

转载 作者:行者123 更新时间:2023-12-02 11:07:16 24 4
gpt4 key购买 nike

尽管使用了 attend 方法,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");
}

}
}

关于java - 使用 printwirter attend 方法的 while 循环仅写入最后搜索的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50872305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com