java关于文件处理的方法(xml处理)总结

首先是关于xml文件的操作工具类,可以操作字符串和系统中的本地xml文件,直接生成Map类型的封装数据,很方便操作,代码赋值就可用,主要jar包是dom4j。

代码部分:

package com.chunqiu.wmp.cases.readFile;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;

import java.io.File;
import java.io.InputStream;
import java.io.StringReader;
import java.util.*;


public class XMLReader {
        public static Document doc=null;
        
        public XMLReader(String xmlstr){
            try{
            	StringReader read = new StringReader(xmlstr);            
            	InputSource source = new InputSource(read);
            	
            	SAXReader reader = new SAXReader();
            	//SAXReader reader = new SAXReader();
                doc = reader.read(source);
            }catch(Exception e){
                e.printStackTrace();
            }finally{
            }
        }
        
        public XMLReader(File file){
            try{
            	SAXReader reader = new SAXReader();
                doc = reader.read(file);
            }catch(Exception e){
                e.printStackTrace();
            }finally{
            }
        }
        
        public XMLReader(InputStream in){
            try{
            	SAXReader reader = new SAXReader();
                doc = reader.read(in);
            }catch(Exception e){
                e.printStackTrace();
            }finally{
            }
        }
        
        public String getRootTagName(){
        	String rslt=null;
        	Element el=doc.getRootElement();
        	rslt=el.getName();
        	return rslt;
        }
        
        public List getAttributes(String xpath) {
            List attrs = null;
            xpath=formatXPath(xpath);
            
            try{
                if(doc==null)return null;
                String path = getXPath(xpath);
                Element node = (Element) doc.selectSingleNode(path);
                attrs = node.attributes();
            }catch(Exception e){
                return null;
            }
            return attrs;
        }
        
        public String getAttribute(String xpath,String attrName){
        	String rslt=null;
        	try{
                if(doc==null)return null;
                Element node = (Element) doc.selectSingleNode(getXPath(xpath));
                rslt = node.attributeValue(attrName);
            }catch(Exception e){
            }
        	return rslt;
        }
        
		public String getAttribute(String xpath) {
			Properties prop=this.getPathAndName(xpath);
			if(prop==null)return null;
			return this.getAttribute(prop.getProperty("path"), prop.getProperty("name"));
        }
		
		public String getText(String xpath) {
            
            try{

                if(doc==null)return null;

                Element node = (Element) doc.selectSingleNode(getXPath(xpath));
                return node.getText();
            }catch(Exception e){
                return null;
            }
        }
		
		public Map getNode(String xpath){
			return toMap(xpath);			
		}
		
		public Map getNode(Element node){
			return Dom2Map(node);
		}
		
		public List getNodes(String xpath){
			return doc.selectNodes(getXPath(xpath));			
		}
		
        public Map getRootNode(){
        	return Dom2Map(doc);
        }
		public Map getRootNode2(){
			return Dom2Map2(doc);
		}
        public Document getDecument(){
        	return doc;
        }
        
		private Map toMap(String xpath){
        	 try{
                 if(doc==null)return null;
                 Element node = (Element) doc.selectSingleNode(getXPath(xpath));
                 return Dom2Map(node);
             }catch(Exception e){
                 return null;
             }
        }
        
        private Map Dom2Map(Document doc){  
        	Map map = new HashMap();  
        	if(doc == null)  return map;  
        	Element root = doc.getRootElement();  
        	for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
				Element e = (Element) iterator.next();
				//System.out.println(e.getName());
				List list = e.elements();
				if (list.size() > 0) {
					map.put(e.getName(), Dom2Map(e));
				} else {
					map.put(e.getName(), e.getText());
				}
			}
        	return map;  
        }  

        private Map Dom2Map(Element e){  
        	Map map = new HashMap();  
        	List list = e.elements();  
        	List attrs = e.attributes();
        	
        	if(list.size() > 0){  
        		
        		for (int i = 0;i < list.size(); i++) {  
        			Element iter = (Element) list.get(i);  
        			List mapList = new ArrayList();  
        			if(iter.elements().size() > 0){  
        				Map m = Dom2Map(iter);  
        				if(map.get(iter.getName()) != null){  
        					Object obj = map.get(iter.getName());  
        					if(!obj.getClass().getName().equals("java.util.ArrayList")){  
        						mapList = new ArrayList();  
        						mapList.add(obj);  
        						mapList.add(m);  
        					}  
        					if(obj.getClass().getName().equals("java.util.ArrayList")){  
        						mapList = (List) obj;  
        						mapList.add(m);  
        					}  
        					map.put(iter.getName(), mapList);  
        				}else{  
        					map.put(iter.getName(), m); 
        				}
        			}else{  
        				if(map.get(iter.getName()) != null){  
        					Object obj = map.get(iter.getName());  
        					if(!obj.getClass().getName().equals("java.util.ArrayList")){  
        						mapList = new ArrayList();  
        						mapList.add(obj);  
        						mapList.add(iter.getText());  
        					}  
        					if(obj.getClass().getName().equals("java.util.ArrayList")){  
        						mapList = (List) obj;  
        						mapList.add(iter.getText());  
        					}  
        					map.put(iter.getName(), mapList);  
        				}else { 
        					map.put(iter.getName(), iter.getText());  
        				}
        			}  
        		}  
        	}else {
        		map.put(e.getName(), e.getText());         		
        	}
        	for(int i=0;attrs!=null && i Dom2Map2(Document doc){
		Map map = new HashMap();
		if(doc == null)  return map;
		Element root = doc.getRootElement();
		for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
			Element e = (Element) iterator.next();
			map.put(e.getName(), Dom2Map2(e));
		}
		return map;
	}

	private Map Dom2Map2(Element e){
		Map map = new HashMap();
		List list = e.elements();
		List attrs = e.attributes();
		System.out.println(attrs.size());
		if(list.size() > 0){

			for (int i = 0;i < list.size(); i++) {
				Element iter = (Element) list.get(i);

				List mapList = new ArrayList();

				Map m = (Map) Dom2Map2(iter);

				if(map.get(iter.getName()) != null){
					Object obj = map.get(iter.getName());
					if(!obj.getClass().getName().equals("java.util.ArrayList")){
						mapList = new ArrayList();
						mapList.add(obj);
						mapList.add(m);
					}
					if(obj.getClass().getName().equals("java.util.ArrayList")){
						mapList = (List) obj;
						mapList.add(m);
					}
					map.put(iter.getName(), mapList);
				}else{
					map.put(iter.getName(), m);
				}
			}
		}else {
			map.put("text", e.getText());
		}
		if(attrs!=null && attrs.size()>0){
			Map atts=new HashMap();
			for(int i=0; i

接下来是对文件的读写进行操作:

在指定目录中创建文件:

	public String creatFile(String fileName){
		String path="C:/OMS/Tomcat7/webapps/dyhj/webService/"+fileName+".xml";
		File f=new File(path);
		if(!f.exists()){
			try {
				boolean createNewFile = f.createNewFile();
				System.out.println(createNewFile);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return path;
	}

将字符创写入文件中:

public void writeToFile(String file,String xml){
		FileWriter writer=null;
	    try {
	      writer = new FileWriter(file);
	      writer.write(xml);
	      writer.flush();
	      writer.close();
	    } catch (IOException e) {
	      e.printStackTrace();
	    }
	}

将字符创以二进制的固定编码方式写入文件中

public void writeToFile(String file,String xml){
		FileWriter writer=null;
	    try {
	      writer = new FileWriter(file);
	      PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"utf-8")));
          out.write(xml);
          out.flush();
          out.close();
	    } catch (IOException e) {
	      e.printStackTrace();
	    }
	}

删除文件操作

 public void delFile(String path){
         File file=new File(path);
         if(file.exists()&&file.isFile())
             file.delete();
     }

 

你可能感兴趣的:(java文件操作,xml读取)