繁体   English   中英

从JAVA项目中读取xml文件

[英]Read xml file from within the JAVA project

我需要知道将xml文件放在Java项目中的位置。 我需要访问放置的xml文件并解析它。 我尝试过使用资源文件夹,但它对我不起作用。 有人可以建议我如何访问放置在JAVA项目中的xml文件。 我正在使用Eclipse IDE。

使用如下课程 -

this.getClass().getClassLoader().getResourceAsStream("path of file");

注意:项目中的这个xml文件结构

+pro
   +src
   +resource
     -test.xml

例:

 public class ReadFile {
        public void testReadFile() {
            InputStream in = this.getClass().getClassLoader()
            .getResourceAsStream("/Resources/tset.xml");
//praparing DOM
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
// by sending input stream as input to DOM
        Document doc = docBuilder.parse(in);
        }
        public static void main(String[] args) {
            ReadFile file = new ReadFile();
            file.testReadFile();
        }
    }

您可以使用maven的结构:Project / src / main / resources

我想这是一个数据xml文件。 如果它是配置文件,更好的方法是通过类路径访问它。 这是放置资源的常见位置,但您可以选择自己的目录。 如果您在打开文件时遇到问题,那么您的路径是不正确的。 首先尝试使用绝对路径打开它。 像d:/workspace/Project/src/main/resources/file.xml之类的东西。 它会奏效。

resources文件夹是放置xml文件的正确文件夹。 如果它没有在该文件夹中找到该文件,则它可能不在类路径中。 因此,将此文件夹添加到项目的类路径中。

转到项目 - >属性 - > Java构建路径 - >源 - >添加文件夹

然后将resources文件夹添加到类路径中。 多数民众赞成......你很高兴......

您需要确保Eclipse将/ resources文件夹包含到应用程序类路径中。

Run Configurations打开启动器,转到Classpath选项卡,如果它不存在 - 添加它。

可以使用this.getClass().getClassLoader().getResource*方法读取该文件。

暂无
暂无

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

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