【问题标题】:Java: Using Command line arguments to process the names of filesJava:使用命令行参数处理文件名
【发布时间】:2011-02-02 15:41:13
【问题描述】:

我正在编写一个程序,它将确定文本文件的行数、字符数和平均字长。对于程序,规范说文件将作为命令行参数输入,我们应该为每个输入的文件创建一个 TestStatistic 对象。如果用户输入多个文件,我不明白如何编写生成 TestStatistic 对象的代码。

【问题讨论】:

    标签: java command-line textinput


    【解决方案1】:

    处理命令行参数最基本的方法是:

    public class TestProgram
    {
        public static void main(final String[] args)
        {
            for (String s : args)
            {
                // do something with each arg
            }
            System.exit(0);
        }
    }
    

    最好的方法是使用为您管理命令行参数的东西。我建议JSAP: The Java Simple Argument Parser

    【讨论】:

    • 您不需要(也不应该)使用 System.exit 来存在。让main方法返回即可。
    • 显式优于隐式,尤其是对于初学者!
    • 嗯,它没有比汇编更明确,所以也许他们应该从那里开始?我不同意,更高的抽象对初学者来说更好。显然,您在某种程度上同意,因为您推荐的是 for-each 构造,而不是更明确的标准 for 循环。
    • 我推荐一个明确的 System.exit(0);这将与显式 System.exit(2) 背道而驰;如果参数有问题,我强烈建议使用 JSAP 而不是手动执行所有这些数组解析。
    【解决方案2】:

    听起来您只需要遍历命令行参数并为每个参数生成一个 TestStatistic 对象。

    例如

    public static void main(String[] args)
    {
       for (String arg : args) {
          TestStatistic ts = new TestStatistic(arg); // assuming 'arg' is the name of a file
       }
       // etc...
    

    【讨论】:

    • 你的代码看起来很奇怪,ts的范围是错误的。如果你有收藏或类似的东西会更清楚。这似乎有点令人困惑。
    【解决方案3】:

    这是对其他一般性答案的扩展,进一步刷新。

    public class TextFileProcessor
    {
        private List testStatisticObjects = new ArrayList();
    
        private void addFile(String fileName)
        {
            testStatisticObjects.add(new TestStatistic(fileName));
        }
    
        public static void main(String[] args)
        {
            TextFileProcessor processor = new TextFileProcessor();
            for (String commandLineArgument : args)
            {
                //consider validating commandLineArgument here
                processor.addFile(commandLineArgument);
            }
            ...
        }
    }
    

    【讨论】:

      【解决方案4】:

      你也可以使用Commons CLI之类的东西来处理命令行。

      【讨论】:

      • 这是一个糟糕的建议,Commons CLI 是一个非常糟糕的库,甚至没有得到维护并且语义很糟糕。
      猜你喜欢
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2021-02-13
      • 2010-11-20
      • 2015-05-01
      • 1970-01-01
      相关资源
      最近更新 更多