XML解析

IO流的使用

File:new File (填路径)

FileInputStream:输入流

FileOutputStream:输出流

read:每次读到下一个字节

write:写入

flust:刷新缓冲区

close:关闭

注:要throws错误

public class javaio {
	public static void main(String[] args) throws IOException{
		File f=new File("E:\\图标\\tp\\10.png");//拿图片本地路径
		FileInputStream in=new FileInputStream(f);//输入流
		String name=f.getName();//拿到图片的name
		File f2=new File("E:\\图标1\\"+name);//要复制到的路径
		FileOutputStream out=new FileOutputStream(f2);//输出流
		
		int length = 0;
		byte[] tmp=new byte[1024];//一次读取大小
		while((length = in.read(tmp))!=-1) {//判断里面是否全部读完,循环读取,read每次读到下一个字节
			out.write(tmp, 0, length);//写入要复制的路径
		}
		in.close();
		out.flush();//刷新缓冲区
		out.close();//关闭
	}

}

xml解析

xml文档

<?xml version="1.0" encoding="UTF-8"?>
<!--config标签:可以包含0~N个action标签 -->
<config>
<!--action标签:可以饱含0~N个forward标签 path:以/开头的字符串,并且值必须唯一 非空 ,子控制器对应的路径 type:字符串,非空,子控制器的完整类名 -->
<action type="test.action.RegisterAction" path="/registerAction">
<forward path="/index.jsp" redirect="true" name="success"/>
<forward path="/register.jsp" redirect="false" name="failed"/>
</action>
<action type="test.action.LoginAction" path="/loginAction">
<forward path="/index.jsp" redirect="false" name="a"/>
<forward path="/welcome.jsp" redirect="true" name="b"/>
</action>
</config>

在java中解析

1.先类名.class.getResourceAsStream

2.new一个SAXReader

3.生成一个文档Document  (reader.read(填输入流))

4.文档.getRootElement()   拿到开头第一个标签

5.开头元素.selectNodes("填标签")  在list里填element强转为元素,不加/

6.foreach循环

7.循环.attributeValue("path")   拿标签下的属性内容

先通过当前标签拿下一个节点

循环嵌套是拿当前标签内的标签属性

public static void main(String[] args) throws Exception{
		//输入流
		InputStream is = XmlReader.class.getResourceAsStream("/config.xml");//要加/在同一个包下则不需要
		SAXReader reader=new SAXReader();//用来读取
		Document doc = reader.read(is);//相当于一个文档
		
		Element e = doc.getRootElement();//获得根元素,也就是开头的第一个标签
		List<Element> actions = e.selectNodes("action");//获得根路径下的action,element强转为元素,不要加/,加了表示从根路径开始
		
		for (Element e2 : actions) {
			String path = e2.attributeValue("path");//拿标签下属性的内容
			String type = e2.attributeValue("type");
			System.out.println(path);
			System.out.println(type);
			List<Element> forward = e.selectNodes("forward");//拿e2下面的子节点
			
			for (Element e3 : forward) {
				String name = e3.attributeValue("name");
				String fpath = e3.attributeValue("path");
				String red = e3.attributeValue("redirect");
				//Boolean.valueOf(red);类型转换转换成Boolean类型
			}
		}
	}

Boolean.valueOf(red);类型转换转换成Boolean类型

这样一个xml文件就解析完了。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值