Jdom简单的修改xml文件实现

时间:2023-03-10 07:12:09
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截取路径,不如拼接