首页 > 解决方案 > 如何在命令行 Java 中从 args 中提取两个路径?

问题描述

我正在制作一个 Huffman Tree 实现,它获取一些数据并打印树的叶子,或者将树序列化为一个文件。该实现使用一个自定义命令行程序,该程序接收标志、源路径 ( ~/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.txtinFile source~/example/dir/inPath outputPath

标签: javacommand-lineparameter-passingcommand-line-argumentsfilepath

解决方案


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

首先,我建议使用这个命令:

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

然后当你点击 -f 时,你设置一个新变量,让我们说“nextParam”到 SOURCE(也许是一个枚举?也可以是一个最终的静态 int 值,如 1)当你点击 -o 时将“nextParam”设置为 OUTPUT

然后在你的开关之前但在循环内(不要忘记添加你应该已经放在你的 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 循环的底部放置一个最终的“else”,将值放入“ source" 除非 source 已经有值,在这种情况下你把它放到 outputFile 中。

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


推荐阅读