簡體   English   中英

Java:使用命令行參數來處理文件名

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

我正在寫一個程序,它將確定文本文件的行數,字符和平均字長。 對於程序,規范說一個或多個文件將作為命令行參數輸入,並且我們應該為每個輸入的文件創建一個TestStatistic對象。 如果用戶輸入多個文件,我不明白如何編寫用於制作TestStatistic對象的代碼。

處理命令行參數的最基本方法是:

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

最好的方法是使用一些為您管理命令行參數的東西。 我建議使用JSAP:Java簡單參數解析器

聽起來您只需要遍歷命令行參數並為每個參數生成一個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之類的東西來處理命令行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM