java - 如何在命令行 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.txt
inFile source
和~/example/dir/
inPath outputPath
解决方案
在读取值时,您需要有状态。
首先,我建议使用这个命令:
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 ,这是没有意义的,因为你只是说两个不匹配的值作为开关被假定为你的文件。
推荐阅读
- reactjs - 如何使用 React Material UI 将不同的颜色阴影传递给组件
- firebase - 云功能中的Firebase时间戳不显示时间
- python - SKLearn 是否有最低硬件要求?
- react-native - React Native Elements 处理 ListItem 点击
- r - 使用 facet_wrap 将 r 平方注释到 ggplot
- iis - Windows Server 2008 R2-命令提示符-php7ts.dll 丢失
- java - 如何在 selenide 中使用 List <> 和 WebElement?
- vue.js - 可排序在带有复选框的 el-table-column 中不起作用
- r - R 脚本视觉。强制 Y 轴值显示为文本
- python-3.x - 如何在 Python 中正确使用迭代器?Python初学者