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<String, Object> Dom2Map(Document doc){  
        	Map<String, Object> map = new HashMap<String, Object>();  
        	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<attrs.size();i++){
        		 Attribute attr=(Attribute) attrs.get(i);
        		map.put(attr.getName(), attr.getData());
        	}
        	return map;  
        } 


	private Map toMap2(String xpath){
		try{
			if(doc==null)return null;
			Element node = (Element) doc.selectSingleNode(getXPath(xpath));
			return (Map) Dom2Map2(node);
		}catch(Exception e){
			return null;
		}
	}

	private Map<String, Object> Dom2Map2(Document doc){
		Map<String, Object> map = new HashMap<String, Object>();
		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<attrs.size();i++) {
				Attribute attr = (Attribute) attrs.get(i);
				atts.put(attr.getName(), attr.getValue());
			}
			map.put("attributes", atts);
		}
		return map;
	}


	private String formatXPath(String xpath){
		xpath = xpath.replace('\\', '/');
		if(xpath.equals("/"))return xpath;

		if(xpath.endsWith("/")){
			xpath=xpath.substring(0,xpath.length()-1);
		}
		return xpath;
	}
        private Properties getPathAndName(String xpath){
        	Properties pro=new Properties();
        	xpath=formatXPath(xpath);
        	if(xpath.length()<=0)return null;
        	if(xpath.indexOf("/")<0){
        		pro.setProperty("path", "/");
        		pro.setProperty("name", xpath);        		
        	}else{
        		pro.setProperty("path", xpath.substring(0,xpath.lastIndexOf("/")));
        		pro.setProperty("name", xpath.substring(xpath.lastIndexOf("/")+1,xpath.length()));  
        	}
        	
        	return pro;
        }
        
        private String getXPath(String xpath){
        	xpath=formatXPath(xpath);
        	if(xpath.equals("/")){
        		xpath="/"+getRootTagName();
        		return xpath;
        	}
        	
        	if(xpath.startsWith("/"))return xpath;
        	
        	xpath="/"+getRootTagName()+"/"+xpath;
			return xpath;

        }
}

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

在指定目录中创建文件:

	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();
     }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils; import java.io.*; /** * FileUtil. Simple file operation class. * * @author BeanSoft * */ public class FileUtil { /** * The buffer. */ protected static byte buf[] = new byte[1024]; /** * Read content from local file. FIXME How to judge UTF-8 and GBK, the * correct code should be: FileReader fr = new FileReader(new * InputStreamReader(fileName, "ENCODING")); Might let the user select the * encoding would be a better idea. While reading UTF-8 files, the content * is bad when saved out. * * @param fileName - * local file name to read * @return * @throws Exception */ public static String readFileAsString(String fileName) throws Exception { String content = new String(readFileBinary(fileName)); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(String fileName, String encoding) throws Exception { String content = new String(readFileBinary(fileName), encoding); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(InputStream in) throws Exception { String content = new String(readFileBinary(in)); return content; } /** * Read content from local file to binary byte array. * * @param fileName - * local file name to read * @return * @throws Exception */ public static byte[] readFileBinary(String fileName) throws Exception { FileInputStream fin = new FileInputStream(fileName); return readFileBinary(fin); } /** * 从输入流读取数据为二进制字节数组. * @param streamIn * @return * @throws IOException */ public static byte[] readFileBinary(InputStream streamIn) throws IOException { BufferedInputStream in = new BufferedInputStream(streamIn); ByteArrayOutputStream out = new ByteArrayOutputStream(10240); int len; while ((len

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值