The following Java 7+ solution has a major 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); } } }
This is no shorter than the code from this answer . The main thing is that when we open File we have an open resource, and we must take care to close it. Otherwise, this could result in a resource leak.
Starting with Java 7, the try-with-resources statement handles resource closures. Thus, opening a Scanner with a file will look like this:
try (Scanner scanner = new Scanner("leaders.txt")) {
Using Files.readAllLines we do not need to worry about closing the file, since this method ( JavaDoc )
ensures that the file is closed after reading all bytes or when an I / O error or other exception occurs at runtime.
If only the first occurrence of String is required, the following Java 8+ code does the work on multiple 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(); } }
Returns Optional indicating that there may be an empty result. We use it, that is, 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); }
source share