我正在尝试读取.jar文件中的初始文本文件。我试图用ClassLoader加载该文件,但它不起作用。奇怪的是,它在Eclipse中以这种方式工作,但它不是单独的可执行jar文件。
现在,我将尝试重现这种情况:
A类:
/**
* Read initial file.
*
* @return initial file
*/
private SomeObject readInitialObject() {
String path = "object/Welcome.xml";
File f = new File(path);
Reader r = new Reader(f);
SomeObject o = r.read();
return o;
}类阅读器:
private File importedFile;
public void read() {
...
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(FileLoader.load(importedFile.
getPath()));
}FileLoader类
/**
* Load input stream.
*
* @param path file path
* @return input stream
*/
public static InputStream load(final String path) {
InputStream input = FileLoader.class.getResourceAsStream(path);
if (input == null) {
input = FileLoader.class.getResourceAsStream("/" + path);
}
return input;
}

如果能收到你的建议,我将不胜感激。谢谢!
发布于 2013-03-29 21:34:35
让我们来看看Distributed jar file not picking up my .txt file的例子。
您需要指定相对于正在使用getResourceAsStream的类的路径
发布于 2013-03-29 21:31:06
在jar文件中,文件结构与实际结构略有不同。您可以打开jar来查看文件的exatcly路径。另请参阅http://docs.oracle.com/javase/tutorial/deployment/jar/build.html
发布于 2013-03-29 21:32:58
问题可能是Windows不区分大小写,但在jar中,文件名区分大小写(就像在Linux上一样)。此外,不要使用文件,并且因为您使用的是/而不是\。
所以我认为实际的文件在另一种情况下。
https://stackoverflow.com/questions/15704221
复制相似问题