gpt4 book ai didi

java - 如何接受文件的命令行参数

转载 作者:行者123 更新时间:2023-12-01 19:56:01 25 4
gpt4 key购买 nike

 public static void main(String[] args) throws FileNotFoundException  {


File inputFile = null;
File outputFile = null;


if (args.length > 0) {
String inputName = args[0];
String outputName = args[1];
inputFile = new File(inputName);
outputFile = new File(outputName);
}else{
Scanner input = new Scanner(System.in);
inputFile = new File(input.next());
outputFile = new File(input.next());
}

}

这是我的代码,它应该检查文件名的命令行参数,但如果没有,它会让用户输入名称。但是我如何让它抛出文件未找到异常?我感谢任何帮助

最佳答案

您最好使用 java.nio.file.Path 而不是旧的 File 类。 java.nio.file.Files 有很多用于 Paths 的实用方法。

您可以检查文件是否存在,然后抛出您自己的FileNotFoundException:

Path path = Path.of(filename);
if (!Files.exists(path)) throw new FileNotFoundException(path.toString());

或者,您可以生成 NoSuchFileException:

path.getFileSystem().provider().checkAccess(path);

关于java - 如何接受文件的命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59042098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com