从WAR文件获取文件

时间:2013-08-06 19:16:16

标签: java url path classloader war

我正在尝试从WAR文件中获取文件。

URL url2 = getClass().getClassLoader().getResource("/package.xsd");

当我打印getPath()时,这是输出:

/C:/workspacesFresh2/.metadata/.plugins/org.eclipse.wst.core/tmp1/wtpwebapps/GServer/WEB-INF/lib/GLibrary.jar!/package.xsd

所以,它找到了package.xsd,但我不能用那条路径打开它。

关于如何访问该文件的任何想法?

错误:

org.xml.sax.SAXParseException; schema_reference.4: Failed to read schema document 'file:/C:/workspacesFresh2/.metadata/.plugins/org.eclipse.server.core/tmp1/wtpwebapps/Server/WEB-INF/lib/GLibrary.jar!/package.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.

由于

2 个答案:

答案 0 :(得分:2)

你无法使用它的路径打开它,因为它不是普通文件,它是jar中的文件。

访问它的一种方法是使用输入流

InputStream stream = this.getClass().
    getClassLoader().getResourceAsStream("/package.xsd");

他们可以从输入流中读取

答案 1 :(得分:0)

URL的“路径”部分不一定与文件系统中的路径相同。实际上,您的URL不是文件URL,因为它指向JAR文件。您无法获取路径并在文件系统中查找它。

如果要在应用程序中访问它,则必须使用流。

另请参阅:URL on Wikipedia