如何在命令行 Java 中从参数中提取两个路径?

How to extract two Paths from args in command-line Java?

我正在制作一个霍夫曼树实现,它获取一些数据并打印树的叶子,或者将树序列化到一个文件中。该实现使用自定义命令行程序来接收标志、源路径 (~/example/dir/source.txt) 和输出路径 (~/example/dir/)。它看起来像

mkhuffmantree -s -f ~/example/dir/source.txt ~/example/dir/ 

我没有使用框架或库来传递命令行参数,我想手动完成。我的解决方案是:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
class mkhuffmantree
{ 
    boolean help = false;
    boolean interactive = false;
    boolean verbose = false;
    boolean serialize = false;
    boolean fromFile = false;
    File source;
    Path outputPath;

  public void readArgs(String[] args){
        for (String val:args) 
        if(val.contains(-h)){
            help = true;
        } else if(val.contains(-i)){
            interactive = true;
        } else if(val.contains(-v)){
            verbose = true;
        } else if(val.contains(-s)){
            serialize = true;
        } else if(val.contains(-f)){
            fromFile = true;
        }
    }

    public void main(String[] args){  
        if (args.length > 0){ 
            readArgs(args);            
        } 
    } 
} 

但是在解释了标志之后,我不知道如何将~/example/dir/source.txt存储在File source,以及~/example/dir/存储在Path outputPath

您在读取值时需要有状态。

首先,我建议改用此命令:

mkhuffmantree -s -f ~/example/dir/source.txt -o ~/example/dir/ 

然后当你点击 -f 时,你设置了一个新变量,假设 "nextParam" 到 SOURCE (也许是一个枚举?也可以是一个最终的静态 int 值,如 1)当你点击 -o set "nextParam"到输出

然后在你的 switch 之前但在循环内(不要忘记添加你应该已经放在 for 语句之后的大括号!)你想要这样的东西:

if(nextParam == SOURCE) {
    fromFile = val;
    nextParam = NONE; // Reset so following params aren't sent to source
    continue;   // This is not a switch so it won't match anything else
}

重复输出

另一种方法:

如果你不想使用-o,还有另一种不需要-f或-o的方法,那就是在for循环的底部放一个final "else" 将值放入 "source" 除非 source 已经有一个值,在这种情况下你将它放入 outputFile.

如果你这样做,你可以完全摆脱 -f ,这是没有意义的,因为你只是说作为开关不匹配的两个值被假定为你的文件。

你可以这样做:

        for (int i = 0; i < args.length; i++) {
            String val = args[i];

            if (val.contains("-h")) {
                help = true;
            } else if (val.contains("-i")) {
                interactive = true;
            } else if (val.contains("-v")) {
                verbose = true;
            } else if (val.contains("-s")) {
                serialize = true;
            } else if (val.contains("-f")) {
                fromFile = true;
                source = new File(args[++i]);
            }
        }

        outputPath = Paths.get(args.length - 1);

此外,请查看 Apache CLI