简体   繁体   中英

File not found altough it exists (Java)

I am trying to read javascript file contents from Java code. 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

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. 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. 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 .

A URL is not a filename, and a resource is not a file. You can't use FileInputStream on it for both reasons. Once the resource is packaged into your JAR file the whole scheme will collapse. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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