public static void main(String[] args) {
File f = new File("path-to-your-file-on-your-system!");
System.out.println(getLineNumber("SlimShady", f));
System.out.println(getLineNumber("Eminem", f));
System.out.println(getLineNumber("MomsSpaghetti", f));
System.out.println(getLineNumber("doodoodoodoo....doooooooooo...dooooooo...can't touch this!", f));
}
private static int getLineNumber(String userName, File usernameFile) {
boolean found = false;
int lineCount = -1;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(usernameFile)))) {
String line;
while ((line = reader.readLine()) != null && !found) {
++lineCount; // increment and get (start at 0)
found = line.trim().equals(userName); // found it?
}
} catch (IOException ex) {
Logger.getLogger(TestMain.class.getName()).log(Level.SEVERE, null, ex);
}
if (!found) {
// we didn't find it... return -1 (an impossible valid value) to handle that scenario.
lineCount = -1;
}
return lineCount; // found it, what line?
}
And running it with only Eminem-related usernames in my totally made-up usernames file (we get a -1 for MC Hammer... apparently we still can't touch this.
run:
1
0
2
-1
BUILD SUCCESSFUL (total time: 0 seconds)