如何使用 FileInputStream 加载配置 xml 文件,但出现 FileNotFoundException
我在 Eclipse 中的构建路径如下所示:
ProjectName
-- WEB-INF
-- classes
-- myClass.class
-- configs
-- myConfig.xml
我的配置的绝对路径当前如下所示:
C:\Development\Java\ProjectName\WEB-INF\configs\myConfig.xml
我正在使用 JAXB 进行绑定,它是期待一个 FileInputStream。 FileInputStream 必须是 XML 配置文件的流。但是,我不知道如何获取配置的 FileInputStream,并且不断收到 FileNotFoundException。
我希望以这样的方式加载此配置,以便某人不必对配置的路径进行硬编码,因为我计划发布该项目开源。我看到很多例子,有人只是硬编码完整的绝对路径,但我需要它是更灵活的“像”这样:
new FileInputStream("/WEB-INF/configs/myConfig.xml");
谢谢!
My build path in Eclipse looks like this:
ProjectName
-- WEB-INF
-- classes
-- myClass.class
-- configs
-- myConfig.xml
My absolute path to the config currently looks like this:
C:\Development\Java\ProjectName\WEB-INF\configs\myConfig.xml
I'm using JAXB for the binding, and it is expecting a FileInputStream. The FileInputStream needs to be a stream for the XML config file. However, I can't figure out how to get the FileInputStream for my config, and I keep getting a FileNotFoundException.
I want this config to be loaded in such a way that someone doesn't have to hardcode the path to the config because I plan on releasing the project open source. I see a lot of examples where someone just hardcodes the full absolute path, but I need it to be something more flexible "like" this:
new FileInputStream("/WEB-INF/configs/myConfig.xml");
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议将 myConfig.xml 放在 WEB-INF/classes 目录中,并通过类加载器加载它,因为它位于类路径中。在 servlet 上下文中调用 getResourceAsStream() 将返回一个可供您使用的 InputStream。它与上下文根相关,因此您可以拾取该 WAR 并将其放在任何地方 - 您的代码仍然可以工作。
I'd recommend putting that myConfig.xml in the WEB-INF/classes directory instead and loading it via the class loader, since it's in the classpath. Calling getResourceAsStream() on the servlet context will return an InputStream that you can use. It's relative to the context root, so you can pick up that WAR and put it anywhere - your code will still work.
您可以使用 ServletContext.getResourceAsStream() 方法相当轻松地获取 WEB-INF 下相对路径的输入流(javadoc 此处)及其变体。
例如,在您的 selvlet 代码中,您可以执行以下操作:
You can get the input stream of relative paths under WEB-INF fairly easily with
ServletContext.getResourceAsStream()
method (javadoc here) and its variants.For example, in your selvlet code you can do this: