Java 未引发FileNotFoundException
我正在编写一段代码,返回用户输入文件名的扫描程序。代码如下:Java 未引发FileNotFoundException,java,try-catch,filenotfoundexception,Java,Try Catch,Filenotfoundexception,我正在编写一段代码,返回用户输入文件名的扫描程序。代码如下: public static Scanner getInputScanner(Scanner console) { System.out.print("Enter input file: "); String fileName = ""; try { fileName = console.nextLine(); File f = new File(fileName); }
public static Scanner getInputScanner(Scanner console) {
System.out.print("Enter input file: ");
String fileName = "";
try {
fileName = console.nextLine();
File f = new File(fileName);
} catch (FileNotFoundException e) {
while (!(new File(fileName)).exists()) {
System.out.println(fileName + " (No such file or directory)");
System.out.print("Enter input file: ");
fileName = console.nextLine();
}
}
File f = new File(fileName);
return new Scanner(f);
}
我有两个错误:
Compression.java:49: error: exception FileNotFoundException is never thrown in body of corresponding try statement
} catch (FileNotFoundException e) {
^
Compression.java:57: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
return new Scanner(f);
我不明白为什么try块没有抛出异常,因为用户可能输入一个无效的文件名
谢谢你的帮助
编辑:将FileNotFoundException更改为NullPointerException,并修复了第一个问题。但是,现在我得到一个错误,返回语句抛出了一个未报告的FileNotFoundException。但是除非文件有效,否则代码不会执行,对吗?Java是否对此视而不见,并要求我捕获异常
return new Scanner(f);
当找不到文件时抛出错误,它无法返回扫描仪(f)
。所以应该包装在try catch
块中
或者,您需要使用getInputScanner
抛出FileNotFoundException来明确说明文件(字符串路径名)
构造函数只能抛出NullPointerException
而不能抛出FileNotFoundException
如果要查看文件名是否有效,请使用
如果文件不存在,则不会引发异常。文件
对象实际上只是一个文件名;它不引用实际的文件。如果该文件不存在,则在尝试使用它时会出现异常
new Scanner(f)
是引发FileNotFoundException
的部分,FileNotFoundException
既不是通过创建新的文件
对象()引发的。这两个函数都不执行与文件I/O相关的操作
Scanner.nextLine()
对alread现有输入源进行操作
File#new()
只创建一个新的File
对象,该对象将(文件名)指向一个(可能存在的)实际文件
相反,创建一个文件涉及创建一个新的InputStream
,因此它实际上通过打开来接触提供的文件
从java.util.Scanner:
您可以在构建扫描仪之前随时调用,如果使用无限循环,则可以简化逻辑并消除这些错误。大概
public static Scanner getInputScanner(Scanner console) {
while (true) {
System.out.print("Enter input file: ");
String fileName = console.nextLine();
File f = new File(fileName);
if (!f.exists()) {
System.out.println(fileName + " (No such file or directory)");
continue;
}
try {
return new Scanner(f);
} catch (FileNotFoundException e) {
// This shouldn't happen.
e.printStackTrace();
System.out.println(fileName + " (No such file or directory)");
}
}
}
public Scanner(File source) throws FileNotFoundException {
this((ReadableByteChannel)(new FileInputStream(source).getChannel()));
}
public static Scanner getInputScanner(Scanner console) {
while (true) {
System.out.print("Enter input file: ");
String fileName = console.nextLine();
File f = new File(fileName);
if (!f.exists()) {
System.out.println(fileName + " (No such file or directory)");
continue;
}
try {
return new Scanner(f);
} catch (FileNotFoundException e) {
// This shouldn't happen.
e.printStackTrace();
System.out.println(fileName + " (No such file or directory)");
}
}
}