Printwriter仅将带有搜索词的最后一行写到文件中,而不是将每个带有搜索词的行写到文件中,尽管使用了Atten方法。我认为我的代码有问题。有人可以检查代码并帮助我吗?
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");
}
}
}