简体   繁体   English

完全找不到文件(Java)

[英]File not found altough it exists (Java)

I am trying to read javascript file contents from Java code. 我正在尝试从Java代码读取javascript文件内容。 Here is my code: 这是我的代码:

 String javascript = "";
 URL url = getClass().getResource("/elementController.js");
 System.out.println(url.toString());
 try {
     Scanner sc = new Scanner(new File(url.getPath()));
     while (sc.hasNext()) {
         javascript += sc.nextLine() + "\n";
     }
     sc.close();

     } catch (Exception e) {
         e.printStackTrace();
     }

System.out.println prints the following: file: /C:/Users/J%c3%bcesse/IdeaProjects/JavaFxProject/target/classes/elementController.js System.out.println打印以下文件:/ C : /Users/J%c3%bcesse/IdeaProjects/JavaFxProject/target/classes/elementController.js

As a result of this code execution I get the following stacktrace: 通过执行此代码,我得到以下堆栈跟踪:

java.io.FileNotFoundException: C:\Users\J%c3%bcesse\IdeaProjects\ThesisProject\target\classes\elementController.js (The system cannot find the path specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at gui.WebViewWindow$MyBrowser.<init>(WebViewWindow.java:82)
at gui.WebViewWindow.display(WebViewWindow.java:58)

But when I go to the directory where the javascript file resides, I can see that it is there. 但是,当我转到javascript文件所在的目录时,可以看到它在那里。 Picture of the directory: 目录图片:

目录结构

I don't know why I am getting this error, even though the file exists there. 即使文件存在,我也不知道为什么会收到此错误。 Any suggestions? 有什么建议么?

The character ü is getting converted to %c3%bc in URL format. 字符ü将以URL格式转换为%c3%bc When you try to use that path as a regular file path for file input, however, instead of opening URL input stream, the reverse decoding of %c3%bc doesn't happen, and the file names don't match, hence the FileNotFoundException . 但是,当您尝试使用该路径作为文件输入的常规文件路径时,不是打开URL输入流,而是不会发生%c3%bc的反向解码,并且文件名不匹配,因此FileNotFoundException

A URL is not a filename, and a resource is not a file. URL不是文件名,资源不是文件。 You can't use FileInputStream on it for both reasons. 出于两个原因,不能在其上使用FileInputStream Once the resource is packaged into your JAR file the whole scheme will collapse. 一旦资源打包到您的JAR文件中,整个方案将崩溃​​。 You need to use the resource's input stream: 您需要使用资源的输入流:

URL url = getClass().getResource("/elementController.js");
System.out.println(url.toString());
try {
    Scanner sc = new Scanner(url.openStream());

As you're only reading lines, there is no good reason to use a Scanner actually: you may as well use a BufferReader . 由于您仅阅读行,因此没有充分的理由实际使用Scanner :您也可以使用BufferReader

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM