如何使用 FileInputStream 加载配置 xml 文件,但出现 FileNotFoundException

发布于 2024-08-20 03:03:27 字数 570 浏览 2 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

唐婉 2024-08-27 03:03:27

我建议将 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.

街道布景 2024-08-27 03:03:27

您可以使用 ServletContext.getResourceAsStream() 方法相当轻松地获取 WEB-INF 下相对路径的输入流(javadoc 此处)及其变体。

例如,在您的 selvlet 代码中,您可以执行以下操作:

getServletContext().getResourceAsStream("/WEB-INF/configs/myConfig.xml") // your file
getServletContext().getResource("/WEB-INF") // URL to WEB-INF dir

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:

getServletContext().getResourceAsStream("/WEB-INF/configs/myConfig.xml") // your file
getServletContext().getResource("/WEB-INF") // URL to WEB-INF dir
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文