把文件放在src 就叫类路径:
类对象获取: 通过类名.class即可

一般使用类对象(类名.class)提供的输入流 getResourceAsStream从源头获取流(// 获取资源成为流),里面的参数写/文件名(返回的是一个输入流对象)
// 注意:只有getResourceAsStream中的/是直接去src下寻找文件
package com.itheima.d1_dom4j;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.io.SAXReader;import org.junit.Test;import java.io.InputStream;/*** 目标:学会使用dom4j(框架)解析XML文件中的数据* 1. 导入dom4j框架* 2. 准备一个XML文件*/public class Dom4JHelloWorldDemo1 {@Testpublic void parseXMLData() throws Exception {// 1. 创建一个Dom4j的解析器对象,代表了整个dom4j框架SAXReader saxReader = new SAXReader();// 2. 把XML文件加载到内存中成为一个Document文档对象// 在开发中不会通过文件名去定位: 因为相对路径的模块名会被改// Document document = saxReader.read(new File("xml-app\\src\\Contacts.xml"));// 一般使用类对象(类名.class)提供的输入流 getResourceAsStream从源头获取流,里面的参数写/文件名(返回的是一个输入流对象)// 注意:只有getResourceAsStream中的/是直接去src下寻找文件InputStream is = Dom4JHelloWorldDemo1.class.getResourceAsStream("/Contacts.xml");Document document = saxReader.read(is); // 把xml文件,读成了文档对象// 3. 获取根元素对象Element rootElement = document.getRootElement();// 获取根元素对象的名字:System.out.println(rootElement.getName()); //<contactList>}}
