Java: Using Command line arguments to process the names of files
I'm a writing a program that will determine the number of lines, characters, and average word length for a text file. For the program, the specifications say that the file or files will be entered as a command line argument and that we should make a TestStatistic object for each file entered. I don't understand how to write the code for making the TestStatistic objects if the user enters mor开发者_如何学Ce than one file.
The most basic way to process command line arguments is:
public class TestProgram
{
public static void main(final String[] args)
{
for (String s : args)
{
// do something with each arg
}
System.exit(0);
}
}
The preferable way is to use something that manages the command line arguments for you. I suggest JSAP: The Java Simple Argument Parser.
It sounds like you simply need to iterate through your command line args and produce a TestStatistic object for each.
e.g.
public static void main(String[] args)
{
for (String arg : args) {
TestStatistic ts = new TestStatistic(arg); // assuming 'arg' is the name of a file
}
// etc...
Here's an expansion on other general answers, flushed out a bit further.
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);
}
...
}
}
You can also use something like Commons CLI to process command line.
精彩评论