Chapter16b.java
Select all
/* Chater16b.java CIS 260 David Klick 2016-02-15 This program demonstrates file input using Files.readAllLines and the String methods startsWith, endsWith, and indexOf. */ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.FileSystems; import java.nio.charset.Charset; import java.util.List; import java.util.ArrayList; import java.io.IOException; public class Chapter16b { private static final boolean DISPLAY = true; public static void main(String[] args) { int match = 0; List
lines; String pat = "kab"; try { Path path = FileSystems.getDefault().getPath("", "dict.txt"); lines = Files.readAllLines(path, Charset.defaultCharset()); int pos = 0; match = 0; System.out.println("Starts with " + pat); for (String line : lines) { if (line.startsWith(pat)) { if (DISPLAY) System.out.println(line); match++; } } if (match == 0) System.out.println("No matches found\n"); else System.out.println(match + " matches found\n"); match = 0; System.out.println("Ends with " + pat); for (String line : lines) { if (line.endsWith(pat)) { if (DISPLAY) System.out.println(line); match++; } } if (match == 0) System.out.println("No matches found\n"); else System.out.println(match + " matches found\n"); match = 0; System.out.println("Index of " + pat); for (String line : lines) { if ((pos = line.indexOf(pat)) != -1) { if (DISPLAY) System.out.println(line + ": Match found at position " + pos); match++; } } if (match == 0) System.out.println("No matches found\n"); else System.out.println(match + " matches found\n"); } catch (IOException e) { System.out.println("Error opening or reading input file"); } } }