[英]File not found altough it exists (Java)
我正在尝试从Java代码读取javascript文件内容。 这是我的代码:
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打印以下文件:/ C : /Users/J%c3%bcesse/IdeaProjects/JavaFxProject/target/classes/elementController.js
通过执行此代码,我得到以下堆栈跟踪:
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)
但是,当我转到javascript文件所在的目录时,可以看到它在那里。 目录图片:
即使文件存在,我也不知道为什么会收到此错误。 有什么建议么?
字符ü
将以URL格式转换为%c3%bc
。 但是,当您尝试使用该路径作为文件输入的常规文件路径时,不是打开URL输入流,而是不会发生%c3%bc
的反向解码,并且文件名不匹配,因此FileNotFoundException
。
URL不是文件名,资源不是文件。 出于两个原因,不能在其上使用FileInputStream
。 一旦资源打包到您的JAR文件中,整个方案将崩溃。 您需要使用资源的输入流:
URL url = getClass().getResource("/elementController.js");
System.out.println(url.toString());
try {
Scanner sc = new Scanner(url.openStream());
由于您仅阅读行,因此没有充分的理由实际使用Scanner
:您也可以使用BufferReader
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.