运行 网络应用程序使用了错误的文件路径

Wrong file path used while running web application

我正在使用 Spring 工具套件开发 Spring 应用程序。我的基本目标是读取现有的 xml 文件并用它做一些事情。 我面临的问题是我无法使用相对文件路径,而 运行 我在服务器上的代码 (tomcat 8.0.18)。但是,如果我测试与 Java 应用程序相同的代码,它运行良好。
我的文件夹结构 -

RootFolder
-- src/main/java
-- -- package_name
-- -- -- FileAccessingClass.java
-- data
-- -- xmlFile.xml

我得到以下错误-

/Users/amit/Desktop/sts-bundle/sts-3.6.3.SR1/STS.app/Contents/MacOS/data/xmlFile.xml (No such file or directory)
Feb 13, 2015 3:27:29 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/metaract] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
    at com.crmantra.metaract.services.ServiceRequests.prepareData(ServiceRequests.java:49)
    at com.crmantra.metaract.services.ServiceRequests.sendRequest(ServiceRequests.java:34)
    at com.crmantra.metaract.controllers.LoginController.login(LoginController.java:27)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

我不明白为什么它会尝试在安装我的 STS 的桌面上查找文件。
如果问题不够清楚,请告诉我。任何帮助将不胜感激。

尝试获取相对于类路径的资源。我假设你已经将数据文件夹包含在你的类路径中......然后你可以这样做:

getClass().getResource("/data/xmlFile.xml")

您是否将 Maven 配置为将 data 文件夹的内容与您的工件捆绑在一起?如果您不是特别喜欢这个文件夹,只需将它放在 /src/main/resources 中并将其称为 /filename.xml 作为资源名称