我正在尝试访问 jar 中包含的文件。
我的代码开头如下:
import java.io.*;
import java.net.*;
public class intro {
public static void main(String[] args) throws IOException{
URL jarUrl = intro.class.getResource("myFile.jar");
File myJar = new File(jarUrl.toString());
FileInputStream fis = new FileInputStream(myjar);
}
我收到以下错误:
Exception in thread "main" java.io.FileNotFoundException: file:\...myFile.jar (The filename, directory name, or volume label syntax is incorrect)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at intro.main(intro.java:10)
查找 URL 或初始化文件似乎没有问题,但我无法让 FileInputStream 工作。有人知道我做错了什么吗?如有帮助,我们将不胜感激。
最佳答案
您无法以这种方式访问 Jar'ed 资源。 Jar 中的文件不是 File
(即文件系统文件中的文件),它们是不同的概念。
您应该使用URL.openStream
。
InputStream is = null;
try {
is = jarURL.openStream();
// ... Read from stream
} catch (IOException exp) {
} finally {
try {
if (is != null) {
is.close();
}
} catch (Exception exp) {
}
}
关于java - 使用 FileInputStream 时出现 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12434292/