Springboot 创建的maven项目 打包后获取resource下的资源文件的两种方式:
资源目录:
resources/config/wordFileXml/wordFileRecord.xml 文件信息
获取方式如下:
一:代码打成jar包,lib文件夹和config配置文件同时复制到同一个linux文件夹里面,启动jar文件,获取当前config文件夹的配置文件资源
资源结构:
获取方式:
/** * 获取lib + jar + resource 方式的resource配置文件中的文件 */ Document document = Dom4jUtil.getDocument("config/wordFileXml/wordFileRecord.xml"); //指定未编译,直接IntelliJ IDEA 创建的maven目录 //调用下面方法..... /** * 根据xml路径获得Document文本对象 * 微服务,打成完成的jar,不能再 * @param path xml路径 * @return Document对象 */ public static Document getDocument(String path) { System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>:"+path); /** * 获取普通服务的方式 * lib + jar + resource配置文件 */ SAXReader reader = new SAXReader(); Document document = null; try { //获取当前线程 Thread t=Thread.currentThread(); //获取当前线程的classLoader ClassLoader c=t.getContextClassLoader(); //获取resouce下面指定文件的file路径(相对路径转绝对路径,将%20的乱码转为空格) String filePath=c.getResource(path).getFile().replaceAll("%20", " "); document=reader.read(filePath); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } return document; }
二:代码+lib + resource配置文件 全部打成jar包,直接启动jar文件,获取当前config文件夹的配置文件资源(通过stream 流的方式获取配置信息)
资源结构:
获取方:
/** * 微服务获取resource配置文件方式 * lib、代码、打包到整个jar包中 * 获取jar包中的resource配置文件中的文件 */ Document document = Dom4jUtil.getDocument("/BOOT-INF/classes/config/wordFileXml/wordFileRecord.xml"); //指定编译后的jar包中的文件目录,否则找不到 //调用下面方法....... /** * 根据xml路径获得Document文本对象 * 微服务,打成完成的jar,不能再 * @param path xml路径 * @return Document对象 */ public static Document getDocument(String path) { System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>:"+path); /** * 微服务获取resouce配置文件方式 * jar包,resouce,代码,全部再一个jar里面, * 通过流的形式获取配置文件,然后转为xml文件 */ Document document = null; Thread t=Thread.currentThread(); //返回读取指定资源的输入流 InputStream is = t.getClass().getResourceAsStream(path); //字节流转为字符流,并输出拼接为字符串 BufferedReader br=new BufferedReader(new InputStreamReader(is)); String s=""; String xml=""; try { //循环输出,拼接 while((s=br.readLine())!=null){ xml+=s; } } catch (IOException e) { log.error("Dom4jUtil ———> getDocument 获取xml流文件信息报错,原因:" +e.getMessage()); // e.printStackTrace(); } try { //将字符串转换为xml格式,返回document document = DocumentHelper.parseText(xml); } catch (DocumentException e) { log.error("Dom4jUtil ———> getDocument 创建document对象错误,原因:" +e.getMessage()); document = null; // e.printStackTrace(); } return document; }