Java Scanner(文件(字符串路径名))提供FileNotFoundException,而Scanner(文件(URI))提供don';对于相同的资源。为什么?

Java Scanner(文件(字符串路径名))提供FileNotFoundException,而Scanner(文件(URI))提供don';对于相同的资源。为什么?,java,java.util.scanner,Java,Java.util.scanner,此操作失败,新扫描仪(文件)中出现FileNotFoundException: 但这运行正常,没有任何异常(同一个包中的类): 你怎么了 String fileName = Ex1.class.getResource("/boot.txt").toExternalForm(); File file = new File(fileName); Scanner sc = new Scanner(file); 有助于扫描器之间的“奇怪”差异,但没有回答这个问题…那么在不工作的版本中,fileNa

此操作失败,新扫描仪(文件)中出现FileNotFoundException:

但这运行正常,没有任何异常(同一个包中的类):

你怎么了

String fileName = Ex1.class.getResource("/boot.txt").toExternalForm();
 File file = new File(fileName);
 Scanner sc = new Scanner(file);

有助于扫描器之间的“奇怪”差异,但没有回答这个问题…

那么在不工作的版本中,
fileName
的值是多少?为什么要通过
文件
?除此之外,如果
boot.txt
在jar文件中,那么这将不起作用。无论如何,这两种方法都是错误的,并且一旦资源被捆绑到jar/war文件中进行生产,这两种方法就不起作用。只需使用
Ex1.class.getResourceAsStream(“/boot.txt”)
,并将InputStream(和字符集)传递给Scanner构造函数。
public class Ex2 {

public static void main(String[] args) {

    URL fileURL = Ex2.class.getResource("/boot.txt");
    Scanner sc;

    try {
        File file = new File(fileURL.toURI());  
        sc = new Scanner(file);  // fine!
    } catch (FileNotFoundException | URISyntaxException e) {            
        e.printStackTrace();
    }       
}
String fileName = Ex1.class.getResource("/boot.txt").toExternalForm();
 File file = new File(fileName);
 Scanner sc = new Scanner(file);