简体   繁体   English

与项目结构相关的getResourceAsStream路径?

[英]getResourceAsStream path related to project stucture?

I know this should be simple, but surprisingly I can't google an answer. 我知道这应该很简单,但是令人惊讶的是我无法在Google上找到答案。

I have this structure : 我有这个结构:

Myproj 的Myproj

|-src | -src

|--com.mypackagename | --com.mypackagename

|---MyClass.java | --- MyClass.java

|-xml | -xml

|--book.xml | --book.xml

XMLInputFactory factory = XMLInputFactory.newInstance();
ClassLoader cl = MyClass.class.getClassLoader();
XMLStreamReader reader = factory.createXMLStreamReader(cl.getResourceAsStream("xml/book.xml"));

and it doesn't find my xml. 而且找不到我的xml。 Obviously, the path is wrong. 显然,路径是错误的。 Please, help me - how shall i set it right 请帮帮我-我该如何正确设置

The problem is that getResourceAsStream() will only load resources from the classpath. 问题在于getResourceAsStream()将仅从类路径加载资源。 And as per given directory your xml file is not located on classpath. 并且根据给定目录,您的xml文件不在classpath上。 So, place your xml file under WEB-INF/classes/book.xml and access it as: 因此,将您的xml文件放在WEB-INF / classes / book.xml下,并按以下方式访问它:

getResourceAsStream("book.xml")

如果将book.xml文件保存在类路径中,则只需编写cl.getResourceAsStream("book.xml")即可对其进行访问。

Assuming that the xml directory is not within the classpath context of your application (ie embedded within the application Jar or with the classpath property), then you will need to reference the XML file as a File . 假设xml目录不在应用程序的类路径上下文中(即,嵌入在应用程序Jar中或具有classpath属性),那么您将需要将XML文件引用为File The path to which will be relative to the execution location of the program. 相对于程序执行位置的路径。

If the xml directory is within the classpath context (ie classpath=.\\xml;... ), then you will need to use a path something like /book.xml . 如果xml目录在classpath上下文内(即classpath=.\\xml;... ),那么您将需要使用类似/book.xml的路径。

If the xml directory is relative to the classpath context (ie classpath=.;... ), then you will need to use a path something like /xm/book.xml . 如果xml目录是相对于classpath上下文的(即classpath=.;... ),那么您将需要使用/xm/book.xml类的路径。

If the xml directory is embedded within the application context (packaged within the Jar), then you will need use either /book.xml or /xml/book.xml depending on how the directory is packaged 如果xml目录嵌入在应用程序上下文中(打包在Jar中),那么根据目录的打包方式,您将需要使用/book.xml/xml/book.xml

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM