【发布时间】:2014-02-03 04:12:35
【问题描述】:
我已经阅读了关于这个主题的每一个问题和答案,并且我尝试了许多建议的解决方案,但都没有奏效,目前我正在尝试使用 URL 资源方法,但 url 总是返回 null。这是我当前的伪设置:
/src/java/pkg/name/is/long/meatpackage/MyClassFile.java
/src/java/pkg/name/is/long/meatpackage/myresources/myresourcefile.txt
@SuppressWarnings("rawtypes")
Class thisClass = Class.forName("pkg.name.is.long.meatpackage.MyClassFile");
ClassLoader cLoader = thisClass.getClassLoader();
//note, I have tried a plethora of variations to the path for the file, this is just one example
URL url = cLoader.getResource("pkg/name/is/long/meatpackage/myresources/myresourcefile.txt");
System.out.println("Found the file!!: " + url);
说真的,在你的 jar 中包含一个文本文件并在运行时访问它不是很难吗?
当我列出 jar 时,它显示该文件位于 pkg/name/is/log/meatpackage/myresources/myresourcefile.txt 中。
我尝试过的另一种方法是:
//along with multiple path combinations for the file the InputStream is always null.
//multiple paths include but are not limited to:
// "pkg/name/is/long/meatpackage/myresources/myresourcefile.txt"
// "/pkg/name/is/long/meatpackage/myresources/myresourcefile.txt"
// "/myresources/myresourcefile.txt"
// "/myresourcefile.txt"
// "myresourcefile.txt"
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("myresourcefile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
【问题讨论】:
标签: java url io classloader getresource