Very basic question on how BufferedReader works. Given the string/phrase, I want to find and print it from the file with a lot of text in it.
using BufferedReader in Java I did some research on this topic and that was the closest result. Not quite addressing my problem though.
So with this information, why does the following code terminate?
public class MainApp {
String line = null;
String phrase = "eye";
try {
File file = new File("text.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while((line = br.readLine()) != null) {
if (line.equals(phrase) {
System.out.println(line);
}
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
My understanding of how this block should work:
Why I think it might not work:
readlines are not stored as strings in the BufferedReader (therefore they can't be compared)
faulty logic (most likely the if statement)
For the sake of simplicity, let's assume that "text.txt" is filled with very long lore ipsum with a single "eye" word put somewhere in the middle of it.
Where exactly is the problem? (Don't provide the entire code solution if possible, I'd love to do the coding part myself for the sake of practice).
Your code should work. The BufferedReader Class
just read buffers of data from the stream. It just means it does not read byte by byte from the file (which would take an eternity to execute).
What the BufferedReader Class
will do is read a buffer of bytes from the file (1024 bytes for instance). It will look for a line separator ("\n") in the buffer. If not found, the bytes will be appended in a StringBuilder
object and the next buffer will be fetched. This will happen until a line separator is found in the buffer. All bytes in the buffer up until the line separator will be appended to the StringBuilder
object, and finally the String will be returned to you.
Edit: depending on implementation, the line separator might or might not be included in the String. Other people pointed out contains()
, however, it would be a lot slower. If you want to find a specific line, do it with equals()
(Add the line separator in the phrase String). If you want to find a specific phrase within a line, then contains()
is the way to go.