Java FileNotFoundException。工作和不工作';你不能同时工作吗?

Java FileNotFoundException。工作和不工作';你不能同时工作吗?,java,jar,getresource,Java,Jar,Getresource,我在一个名为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

我在一个名为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
第一个
系统.out
(1)表示:

第二个
系统.out
(2)表示:

第四行抛出一个

java.io.FileNotFoundException: de/fhg/scai/bio/harsha/classificationworkflow/tagdict.txt (No such file or directory)
文件
tagdict.txt
Method.class
放在同一个包中,即
de/fhg/scai/bio/harsha/classificationworkflow


我不明白为什么第4行抛出一个
FileNotFoundException
,即使该文件已经在jar中找到。

第3行只是打印出
getResource
返回的URL的路径组件。它实际上并不检查该路径是否代表磁盘上的真实文件

看起来
POSDictionary
构造函数正在尝试使用传递给它的路径字符串创建
文件
,而该路径实际上并不表示磁盘上的文件,因此引发异常

我不明白为什么第4行抛出FileNotFoundException,即使该文件已经在jar中找到了


因为如果资源在JAR中,那么它就不是文件。只能通过直接从
URL
对象打开输入流,或者使用
getResourceAsStream()
而不是
getResource()
来访问这些资源。无法使用
java.io.File
访问它们,因为它们不是实际的磁盘文件。

拥有
POSDictionary
的构造函数的代码会有所帮助,因为异常会在那里抛出。
de/fhg/scai/bio/harsha/classificationworkflow/tagdict.txt
java.io.FileNotFoundException: de/fhg/scai/bio/harsha/classificationworkflow/tagdict.txt (No such file or directory)