2014-10-31 99 views
1

我在写一段代码,它返回用户输入文件名的扫描器。下面的代码:FileNotFoundException不被抛出

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并解决第一个问题。但是,现在我得到一个错误,我的return语句抛出一个未报告的FileNotFoundException。但是这个代码不会执行,除非该文件是有效的,对吧? Java对此是否是盲目的,并且要求我捕捉异常呢?

回答

0

The documentation明确指出,File(String pathname)构造函数只能抛出NullPointerException和NOT FileNotFoundException

如果要查看文件名是否有效,请使用f.exists()

0
return new Scanner(f); 

当文件未找到时抛出错误,它不能返回scanner(f)。所以应该包裹在try-catch区块中。

,或者你需要做getInputScannerFileNotFoundException

0
File f = new File(fileName); 

确实如果文件不存在抛出异常。 A File对象实际上只是一个文件名;它不涉及实际的文件。如果该文件不存在,当您尝试使用该文件时,您将收到异常。

new Scanner(f)是抛出FileNotFoundException的部分。

0

FileNotFoundException既不会被Scanner#nextLine()抛出,也不会创建新的File对象(File#new(String))。这两个函数都不会做任何与文件I/O相关的操作。

  • Scanner.nextLine()所操作的alread现有输入源
  • File#new()简单地创建一个新的File对象点(文件名)到(可能存在的)实际文件。

相反,创建new Scanner object涉及创建一个新的InputStream,因此它实际上通过打开提供的文件来触及它。

java.util。扫描仪

public Scanner(File source) throws FileNotFoundException { 
    this((ReadableByteChannel)(new FileInputStream(source).getChannel())); 
} 
0

您可以随时拨打File.exists()您建造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)"); 
     } 
    } 
} 
相关问题