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 words, boolean insens) { Scanner in = new Scanner(line); in.useDelimiter("[^A-Za-z]+"); while (in.hasNext()) { String wordInLine = in.next(); for (String word : words) { if (insens && wordInLine.equalsIgnoreCase(word) || wordInLine.equals(word)) { return true; } } } return false; }

/** 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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!