【发布时间】:2011-02-02 15:41:13
【问题描述】:
我正在编写一个程序,它将确定文本文件的行数、字符数和平均字长。对于程序,规范说文件将作为命令行参数输入,我们应该为每个输入的文件创建一个 TestStatistic 对象。如果用户输入多个文件,我不明白如何编写生成 TestStatistic 对象的代码。
【问题讨论】:
标签: java command-line textinput
我正在编写一个程序,它将确定文本文件的行数、字符数和平均字长。对于程序,规范说文件将作为命令行参数输入,我们应该为每个输入的文件创建一个 TestStatistic 对象。如果用户输入多个文件,我不明白如何编写生成 TestStatistic 对象的代码。
【问题讨论】:
标签: java command-line textinput
处理命令行参数最基本的方法是:
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。
【讨论】:
听起来您只需要遍历命令行参数并为每个参数生成一个 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...
【讨论】:
这是对其他一般性答案的扩展,进一步刷新。
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);
}
...
}
}
【讨论】:
你也可以使用Commons CLI之类的东西来处理命令行。
【讨论】: