如何从命令行Java中的args中提取两个路径?

问题描述 投票:0回答:2

我正在制作一个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.txt中存储File source,在~/example/dir/中存储Path outputPath

java command-line parameter-passing command-line-arguments filepath
2个回答
0
投票

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

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

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

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

然后在你的开关之前,但在循环内部(不要忘记添加你应该在你的声明之后放置的大括号!)你想要的东西如下:

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循环的BOTTOM放置一个最终的“else”,将值放入“ source“除非source已经有一个值,在这种情况下你将它放入outputFile。

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


0
投票

你可以这样做:

        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

© www.soinside.com 2019 - 2024. All rights reserved.