如何读取命令行参数的一部分?

时间:2017-07-26 13:04:47

标签: java command-line arguments

我正在尝试编写一个程序,用于搜索文件中的关键字并打印出包含一个或多个关键字的所有行。命令行选项包括-i(使搜索不区分大小写。), - max n(打印出最多n行。)和-k文件(包含关键字的文件。)

当它工作时,java搜索-max 10 -k keywords.txt input.txt, 打印包含一对或多个keywords.txt关键字的input.txt的前十行。由于未设置-i选项,因此比较区分大小写。

我无法使命令行参数选项的关键字部分生效。这就是我到目前为止所拥有的。有关如何使我的程序工作的任何建议?

        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;
          String keywords = " ";
          int count = 0;

       while (count < args.length)
       {
         String arg = args[count];
         if (arg.startsWith("-"))
         {
            String opt = arg.substring(1);
            if (opt.equals("max"))
            {
               count++;
               max = Integer.parseInt(args[count]);
            }
            else if(opt.equals("i"))
            {
               insens = true;
            }
            else if(opt.equals("k"))
            {
               ???
            }
            else
            {
               usage();
            }
         }
         else if (keywordFile == null)
         {
            keywordFile = arg;
         }
         else if (inFile == null)
         {
            inFile = arg;
         }
         else
         {
            usage();
         }
         count++;
         }

      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<String> 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);
   }
}

0 个答案:

没有答案