java项目中有个xml文件,如何设置路径才可以在本机上的jar,局域网的别的电脑也能读写xml?
2个回答
展开全部
我刚不久前也遇到这类问题,你是要在Java类中读取xml文件,是吗?
我开始写的在本地可以读,可发布了就读不到了,后来就改了如下的方式,供你参考吧:
@SuppressWarnings("unchecked")
public Advice getAdvicefromXML(String type){
Advice advice = new Advice();
SAXReader reader = new SAXReader();// 构建sax读取对象system_advices.xml
try {
InputStream in =[当前这类名(不能用this代替)].class.getClassLoader().getResourceAsStream("system_advices.xml");
Document doc = reader.read(in);// 获取文档对象
//之前我用的这行代码,本地可以,打包了就路径对不上
// Document doc = reader.read("../webapps/manager/WEB-INF/classes /system_advices.xml");// 获取文档对象
Element root = doc.getRootElement();// 获取根节点
List list = root.elements();
for (int i = 0; i < list.size(); i++) {
Element ele = (Element) list.get(i);
if(type.equals(ele.elementText("type"))){
advice.setId(Long.valueOf(ele.elementText("id")));
advice.setTitle(ele.elementText("title"));
advice.setContent(ele.elementText("content"));
advice.setSenderId(ele.elementText("senderid"));
advice.setReceiverType(ele.elementText("type"));
advice.setStatus("1");
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return advice;
}
//核心的代码就这几句
SAXReader reader = new SAXReader();
InputStream in =[当前这类名(不能用this代替)].class.getClassLoader().getResourceAsStream("system_advices.xml");
Document doc = reader.read(in);// 获取文档对象
我开始写的在本地可以读,可发布了就读不到了,后来就改了如下的方式,供你参考吧:
@SuppressWarnings("unchecked")
public Advice getAdvicefromXML(String type){
Advice advice = new Advice();
SAXReader reader = new SAXReader();// 构建sax读取对象system_advices.xml
try {
InputStream in =[当前这类名(不能用this代替)].class.getClassLoader().getResourceAsStream("system_advices.xml");
Document doc = reader.read(in);// 获取文档对象
//之前我用的这行代码,本地可以,打包了就路径对不上
// Document doc = reader.read("../webapps/manager/WEB-INF/classes /system_advices.xml");// 获取文档对象
Element root = doc.getRootElement();// 获取根节点
List list = root.elements();
for (int i = 0; i < list.size(); i++) {
Element ele = (Element) list.get(i);
if(type.equals(ele.elementText("type"))){
advice.setId(Long.valueOf(ele.elementText("id")));
advice.setTitle(ele.elementText("title"));
advice.setContent(ele.elementText("content"));
advice.setSenderId(ele.elementText("senderid"));
advice.setReceiverType(ele.elementText("type"));
advice.setStatus("1");
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return advice;
}
//核心的代码就这几句
SAXReader reader = new SAXReader();
InputStream in =[当前这类名(不能用this代替)].class.getClassLoader().getResourceAsStream("system_advices.xml");
Document doc = reader.read(in);// 获取文档对象
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询