gpt4 book ai didi

java - FileNotFoundException。同时工作和不工作?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:23:46 25 4
gpt4 key购买 nike

我在名为 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

第一个 System.out (1) 说:

rsrc:de/fhg/scai/bio/harsha/classificationworkflow/tagdict.txt

第二个 System.out (2) 说:

de/fhg/scai/bio/harsha/classificationworkflow/tagdict.txt

第 4 行抛出一个

java.io.FileNotFoundException: de/fhg/scai/bio/harsha/classificationworkflow/tagdict.txt (No such file or directory)

文件tagdict.txtMethod.class放在同一个包里,就是de/fhg/scai/bio/harsha/classificationworkflow

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

最佳答案

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

看起来 POSDictionary 构造函数正在尝试使用传递给它的路径字符串创建一个 File,而这个路径实际上并不代表磁盘上的文件,因此抛出异常。

I do not understand why line 4 throws a FileNotFoundException even though the file was found already inside the jar.

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

关于java - FileNotFoundException。同时工作和不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8892356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com