开发者

Java: Using Command line arguments to process the names of files

开发者 https://www.devze.com 2022-12-25 07:37 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号