java - Searching a String in a file -
i wish write function in java searches specific string in text file. loop should use , how? (say while loop, what's condition?)
the used loop while
loop, because need loop , compare if string retired file not null
. well, said, let's see code. solution can write open file first in bufferedreader
instance you'll read line line , see if line contains string looking for. if does, can use boolean
variable , assign true, else assign false. can have in java :
public static boolean findstringfile(string lookingforme, string pathfile) { boolean found = false; try{ bufferedreader br = new bufferedreader(new filereader(pathfile)); try{ string line; while ((line = br.readline()) != null) { if (line.contains(lookingforme)) found = true; } } { br.close(); } } catch(ioexception ioe) { system.out.println("error while opening file !"); } return found; }
this function string lookingforme
first parameter representing string you're searching in file, second parameter string pathfile
represents file's path (it can nameofthefile.extension
when in project's root).
hope you.
edit
the execution of following portion of code (below) isn't successful, if have problem file (file not exist or cannot opened due privilege or else) or other problem, execution stop , throw exception.
bufferedreader br = new bufferedreader(new filereader(pathfile)); string line; while ((line = br.readline()) != null) { if (line.contains(lookingforme)) found = true; }
the goal of "try" avoid these kind of problems displaying user error message (the 1 specified system.out.println("your error message")
).
the appropriate code (to avoid problems listed above) should use 1 try block (the first one).
for further explanation exceptions in java, recommend visiting : https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html