gpt4 book ai didi

java - 在 Eclipse 中放置配置文件的正确位置

转载 作者:行者123 更新时间:2023-11-30 04:32:30 25 4
gpt4 key购买 nike

我在 Eclipse 中创建了一个动态 Web 项目,并且有一个需要读取配置文件的以下 Java 语句:

 Document doc= new SAXReader().read(new File(ConstantsUtil.realPath+"appContext.xml"));

基本上,ConstantsUtil.realPath 将返回一个空字符串。

我尝试将“appContext.xml”放在“src”文件夹和“WEB-INF”文件夹下。但是,我总是会收到以下错误:

 org.dom4j.DocumentException: appContext.xml (The system cannot find the file specified)

我真的很困惑:在 Eclipse 中,放置配置 xml 文件的正确位置在哪里?

提前致谢。

最佳答案

您的具体问题是由于在您完全没有控制本地磁盘当前工作目录的环境中使用带有相对路径的new File()引起的文件系统。所以,算了吧。您需要通过其他方式获取它:

  1. 直接从类路径(src 文件夹,您的 Java 类也在那里)使用 ClassLoader#getResourceAsStream() :

    Document doc= new SAXReader().read(Thread.currentThread().getContextClassLoader().getResourceAsStream("appContext.xml"));
  2. 直接从公共(public)网络内容(WebContent 文件夹,其中 /WEB-INF 文件夹所在)使用 ServletContext#getResourceAsStream() :

    Document doc= new SAXReader().read(servletContext.getResourceAsStream("/WEB-INF/appContext.xml"));

    ServletContext 位于继承 getServletContext() 可用的 servlet 中。方法。

另请参阅:

关于java - 在 Eclipse 中放置配置文件的正确位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14315060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com