XML配置文件和对象的互相转化(使用Digester)

以下是本人编写的 XML配置文件和对象的互相转化 的小例子。

 

package faengine; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.io.*; import org.apache.commons.digester.Digester; public class TestXML extends FAEngineBase { private static final Map FA_MAP = new HashMap(); private FAEngineEntity faEngineEntity; private static Digester digester; public InputStream test() throws IOException { File file = new File("d://ac.xml"); BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); System.out.println(in.toString()); File file1 = new File("d://a.txt"); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file1)); int bytesRead; StringBuffer sb = new StringBuffer(); byte[] buf = new byte[4*1024]; while((bytesRead = in.read(buf)) != -1) { out.write(buf, 0, bytesRead); sb.append(bytesRead); } out.flush(); out.close(); in.close(); System.out.println("sb is " + sb); return in; } public static void main(String[] args) throws IOException { TestXML t = new TestXML(); t.digestMethod(t.test()); Iterator it = FA_MAP.entrySet().iterator(); while(it.hasNext()) { Entry entry = (Entry)it.next(); System.out.println(entry.getKey() + " and " + entry.getValue()); } } private void digestMethod(InputStream is) { if(is==null){ throw new RuntimeException(" inputStream is null!!!" ); } try { digester = new Digester(); digester.push(this); digester.setValidating(false); digester.setNamespaceAware(false); //增加规则 addConfigItemRules(digester); // digester.parse(is); } catch (Exception ex) { ex.printStackTrace(); } } private void addConfigItemRules(Digester digester) { digester.addObjectCreate("calFinancialAccounts/accountCalEssentials", FAEngineEntity.class); digester.addSetProperties("calFinancialAccounts/accountCalEssentials", "setAccountCode", "0"); digester.addSetProperties("calFinancialAccounts/accountCalEssentials", "setCalLevel", "1"); digester.addSetNext("calFinancialAccounts/accountCalEssentials", "addFAMAP"); } public void addFAMAP(FAEngineEntity faEngineEntity) { System.out.println("faEngineEntity.getAccountCode() is " + faEngineEntity.getAccountCode()); System.out.println("faEngineEntity.getCalLevel() is " + faEngineEntity.getCalLevel()); FA_MAP.put(faEngineEntity.getAccountCode(), faEngineEntity.getCalLevel()); } public FAEngineEntity getFaEngineEntity() { return faEngineEntity; } public void setFaEngineEntity(FAEngineEntity faEngineEntity) { this.faEngineEntity = faEngineEntity; } }

你可能感兴趣的:(xml,exception,HashMap,File,iterator,byte)