Lets say I have a string = “hello”. how do i open a text file and check if hello exists in that text file?
contents of the text file:
hello:man:yeah
i tried using the code below. Is it file reader only reads the first line? i need it to check all lines to see if hello exists, and then if it does, take “man” from it.
try {
BufferedReader in = new BufferedReader(new FileReader("hello.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
} catch (IOException e) {
System.out.println("Error.");
}
If hello:man:yeah is one line in your file, then your code is working right. readLine() will read a line until a newline is found (one line in this case).
If you just want to see if it’s in the file, then you could do something like this:
If you need to do a whole word search, you’ll need to use a regular expression. Surrounding your search text with \b will do the whole word search. Here’s a snippet (Note, StringUtils comes from Apache Commons Lang):
Of course, if you don’t have multiple tokens, you can just do this: