Java 如何接受文件的命令行参数
这是我的代码,它应该检查文件名的命令行参数,但是如果没有,它将允许用户输入文件名。但是如何让它抛出文件未找到异常??非常感谢您的帮助您最好使用Java 如何接受文件的命令行参数,java,Java,这是我的代码,它应该检查文件名的命令行参数,但是如果没有,它将允许用户输入文件名。但是如何让它抛出文件未找到异常??非常感谢您的帮助您最好使用java.nio.file.Path而不是旧的文件类java.nio.file.Files有许多用于路径的实用方法 您可以检查文件是否存在,然后抛出自己的FileNotFoundException: Path Path=Path.of(文件名); 如果(!Files.exists(path))抛出新的FileNotFoundException(path.t
java.nio.file.Path
而不是旧的文件
类java.nio.file.Files
有许多用于路径的实用方法
您可以检查文件是否存在,然后抛出自己的FileNotFoundException
:
Path Path=Path.of(文件名);
如果(!Files.exists(path))抛出新的FileNotFoundException(path.toString());
或者,您可以生成一个NoSuchFileException
:
path.getFileSystem().provider().checkAccess(路径);
我会使用input.nextLine()
而不是input.next()
来开始。您可以查看<代码>文件>存在/ <代码>方法,以测试文件是否实际存在,也考虑使用<代码>(AgsSt==2){<代码> >或>代码>(AgsStale>=2){< /C> >,以更好地保护您的意图<代码>如果(true)抛出新的FieloToStudioExptue e;<代码>
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());
}
}