Question: Implement a program that searches for keywords in a file and prints out all lines containing one or more of the keywords. Provide these command-line
Implement a program that searches for keywords in a file and prints out all lines containing one or more of the keywords.
Provide these command-line options:
-i makes the search case-insensitive.
-max n prints out at most n lines.
-k file is the file containing the keywords. This option must be present.
For example,
java Search -max 10 -k keywords.txt input.txt
prints the first ten lines of input.txt containing one or more keywords from keywords.txt. The comparison is case-sensitive since the -i option is not set.
Please use the following code and provide explanation:
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; import java.util.ArrayList;
public class Search { public static void main(String[] args) throws FileNotFoundException { int max = -1; boolean insens = false; String keywordFile = null; String inFile = null; int count = 0;
// TODO: Process command line arguments
Scanner in = new Scanner(new File(inFile)); while (in.hasNextLine()) { String line = in.nextLine(); if (contains(line, keywords, insens) && (max == -1 || count < max)) { System.out.println(line); count++; } } }
/** Checks whether the line contains one or more of the given words. @param line a line @param words a list of words @param insens true if the comparison should be case-insensitive @return true if line contains one or more of words */ public static boolean contains(String line, ArrayList
/** Prints a message describing proper usage and exits. */ public static void usage() { System.out.println("Usage: java Search [-i] [-max n] -k keywordfile file"); System.exit(1); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
