The following Java 7+ solution has a main advantage.
private static void searchForName() throws IOException {
System.out.println("Please enter the name you would like to search for: ");
Scanner kb = new Scanner(System.in);
String name = kb.nextLine();
List<String> lines = Files.readAllLines(Paths.get("leaders.txt"));
for (String line : lines) {
if (line.contains(name)) {
System.out.println(line);
}
}
}
It's not shorter than the the code from this answer. The main point is, when we open a File
we have an open resource and we have to care about closing it. Otherwise it might pose a resource leak.
As of Java 7 the try-with-resources statement handles closing of resources. So opening a Scanner
backed by a file would look like that:
try (Scanner scanner = new Scanner("leaders.txt")) {
// using scanner
}
Using Files.readAllLines
we don't need to care about closing the file since this method (JavaDoc)
ensures that the file is closed when all bytes have been read or an
I/O error, or other runtime exception, is thrown.
If the first occourance of a String
is needed only, the following Java 8+ code does the job in few lines:
protected static Optional<String> searchForName(String name) throws IOException {
try (Stream<String> lines = Files.lines(Paths.get("leaders.txt"))) {
return lines.filter(line -> line.contains(name)).findFirst();
}
}
It returns an Optional
indicating that there might be an empty result. We use it i.e. as follows:
private static void searchForName() throws IOException {
System.out.println("Please enter the name you would like to search for: ");
Scanner kb = new Scanner(System.in);
String name = kb.nextLine();
Optional<String> result = searchForName(name);
result.ifPresent(System.out::println);
}