[英]FileNotFoundException. Works and doesn't work at the same time?
I have the following code in a static class called Methods that is archived in a jar: 我在一个名为Methods的静态类中有以下代码,该类存档在jar中:
System.out.println(Methods.class.getResource("tagdict.txt")); // 1
URL test = Methods.class.getResource("tagdict.txt"); // 2
System.out.println(test.getPath()); // 3
TagDictionary dict = new POSDictionary(test.getPath()); // 4
The first System.out
(1) says: 第一个System.out
(1)说:
rsrc:de/fhg/scai/bio/harsha/classificationworkflow/tagdict.txt
The second System.out
(2) says: 第二个System.out
(2)说:
de/fhg/scai/bio/harsha/classificationworkflow/tagdict.txt
Line 4 throws a 第4行抛出一个
java.io.FileNotFoundException: de/fhg/scai/bio/harsha/classificationworkflow/tagdict.txt (No such file or directory)
The file tagdict.txt
is placed in the same package as the Method.class
, which is de/fhg/scai/bio/harsha/classificationworkflow
. 该文件tagdict.txt
被放置在同一个包中Method.class
,这是de/fhg/scai/bio/harsha/classificationworkflow
。
I do not understand why line 4 throws a FileNotFoundException
even though the file was found already inside the jar. 我不明白为什么第4行抛出FileNotFoundException
即使文件已经在jar中找到了。
Line 3 just prints out the path component of the URL returned by getResource
. 第3行只打印出getResource
返回的URL的路径组件。 It doesn't actually check if that path represents a real file on disk. 它实际上并不检查该路径是否代表磁盘上的真实文件。
It looks like the POSDictionary
constructor is trying to create a File
using the path string passed to it, and this path doesn't actually represent an on-disk file, therefore throwing the exception. 看起来POSDictionary
构造函数正在尝试使用传递给它的路径字符串来创建File
,并且此路径实际上并不表示磁盘上的文件,因此抛出异常。
I do not understand why line 4 throws a FileNotFoundException even though the file was found already inside the jar. 我不明白为什么第4行抛出FileNotFoundException,即使文件已经在jar中找到了。
Because if the resource is in a JAR, then it's not a file. 因为如果资源在JAR中,那么它不是文件。 Such resources can only be accessed by opening input streams directly from the URL
object, or by using getResourceAsStream()
instead of getResource()
. 只能通过直接从URL
对象打开输入流,或使用getResourceAsStream()
而不是getResource()
来访问此类资源。 They can't be accessed using java.io.File
, since they're not actual disk files. 无法使用java.io.File
访问它们,因为它们不是实际的磁盘文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.