Jdom简单的修改xml文件实现

上一篇博客写到在打开outputStream 时总是报错,而且出现jdom有问题,后来注意到junit提示的一个错误:文件过早关闭。

顾名思义:用getResorceAsStream打开了文件作为输入流,但是又用FileOutputStream 又将该文件作为输出流,导致文件不能作为输入流提供给JDom

这里我是这样实现的:

 

package com.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

public class JdomTest2 {
	
public void changeXml() throws JDOMException, IOException {
	
	String path=System.getProperty("java.class.path");  //类路径和包路径
	//获取项目根路径并拼接出文件路径
	//String filePath=System.getProperty("user.dir")+"\\src\\classes\\test.xml";
	
	String filePath=System.getProperty("user.dir")+"\\src\\test.xml";
	System.out.println(filePath);
	//获取输入输出流
	InputStream inputStream =new FileInputStream(new File(filePath));
	
	//设置解释器类
	SAXBuilder sb=new SAXBuilder();
	Document doc=sb.build(inputStream);
	//获取根元素
	Element root=doc.getRootElement();
    //获取根元素下标记为disk的所有子元素
	List allList=root.getChildren("disk");
   
	for(int i=0;i<allList.size();i++)
	{
		Element sigElement=(Element)allList.get(i);
		System.out.println("name:"+sigElement.getAttributeValue("name"));
		System.out.println("capacity:"+sigElement.getChildText("capacity"));
		System.out.println();
	}
	
	//为root添加属性 此时并没有保存到xml文件中
	 root.setAttribute("id", "24235");
    //保存修改到xml文件
	 XMLOutputter outputter=new XMLOutputter(); 
	 outputter.output(doc,new FileOutputStream(filePath));
	//OutputStream outputStram =new FileOutputStream(new File());
}
	
}

这里用System.getProperty("user.dir")获取项目目录,然后再拼接到 所需文件,没有用class().getClass().getResourceAsStream()

因为这个会返回一个URL:file:/G:/text.xml(类似这样的URL路径),还得通过substring截取路径,不如拼接

 

 

转载于:https://www.cnblogs.com/fjsnail/p/3492166.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值