Java 获取jar包中工程下的文件路径的问题

本文介绍了一个使用Java进行XML文件读取与解析的示例程序。该程序通过多种方式定位XML配置文件,并利用DOM解析器读取XML内容,将特定格式的数据转换为Map集合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package main;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class start {

	public static void main(String[] args) throws Exception {
		
		/*File 中可以获取到的路径 jar 中获取不到文件路径*/
		//1、start.class.getResource("../").getPath()+"conf/xconf.xml"
		//2、start.class.getClassLoader().getResource("conf/xconf.xml").getPath()
		//3、File filePath = new File(""); String courseFile = filePath.getCanonicalPath() ;courseFile+"/src/conf/xconf.xml"
		//4、Thread.currentThread().getContextClassLoader().getResource("conf/xconf.xml").getPath()
		//5、new File("./src/conf/xconf.xml").getAbsolutePath()
		//6、"./src/conf/xconf.xml"
		
		Resource res=new Resource();
		String xmlStr = res.getResource(); 
		System.out.println(xmlStr); 
		Map<String, String>  map = new HashMap<String, String>();
		
		StringReader sr = new StringReader(xmlStr);
		InputSource is = new InputSource(sr);
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();   
		DocumentBuilder builder = factory.newDocumentBuilder();   
		Document doc = builder.parse(is);   
		NodeList nodeList = doc.getElementsByTagName("stor");
		for (int i=0;i<nodeList.getLength();i++) {
			Node node = nodeList.item(i);
			String content = node.getTextContent();
			String [] data = content.split("\\|");
			if(data.length==0){
				return;
			}else{
			map.put(new String(Base64.decode(data[0])), new String(Base64.decode(data[1])));
			}
		}
		System.out.println(map);
	}

	}
 

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

〆WangBenYan゜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值