Skip to content

Instantly share code, notes, and snippets.

@dan-dm
Last active May 16, 2020 14:12
Show Gist options
  • Save dan-dm/44e8dec67bab857f7436a5574511c79b to your computer and use it in GitHub Desktop.
Save dan-dm/44e8dec67bab857f7436a5574511c79b to your computer and use it in GitHub Desktop.
Created with Copy to Gist
src/main/java/IsItInTheFile.java
import java.nio.file.Paths;
import java.util.Scanner;
public class IsItInTheFile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Name of the file:");
String file = scanner.nextLine();
System.out.println("Search for:");
String searchedFor = scanner.nextLine();
int lines = 0;
try (Scanner fileReader = new Scanner(Paths.get(file))) {
while (fileReader.hasNextLine()) {
String line = fileReader.nextLine();
if (!line.contains(searchedFor)) {
continue;
}
lines++;
}
} catch (Exception e) {
System.out.println("Reading the file " + file + " failed.");
}
if (lines == 0) {
System.out.println("Not found.");
} else {
System.out.println("Found!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment