<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    posts - 5,  comments - 7,  trackbacks - 0
    今天看了下JAVA序列化。還是一知半解。怎么也沒有弄明白,怎么序列化成XML文件。處入半解狀態(tài)。在網(wǎng)上找了很多,大部分是理論上的。沒有實(shí)際的例子。功夫不負(fù)有心人,終于找到了。做了下測試終于成功。忍不住記錄的下來。

        JXmlSerializable   是一個利用java反射,通過調(diào)用對象中所有以get(不區(qū)分大小寫)開頭的方法除去getClass方法,生成xml格式,希望與大家分享一下  
      下面是一個parent對象,包含兩個child對象  生成的xml如下

        Child類

     1package xmlTest;
     2

     3import
     java.io.FileNotFoundException;
     4import
     java.io.IOException;
     5import
     java.io.PrintWriter;
     6import
     java.lang.reflect.InvocationTargetException;
     7public class Child extends JXmlSerializable 
    {
     8

     9 private
     String _name;
    10 private
     String _sex;
    11 private int
     age;
    12

    13 public void setAge(int num) 
    {
    14  age =
     num;
    15 }

    16
    17 public int getAge() 
    {
    18  return
     age;
    19 }

    20
    21 public void setName(String name) 
    {
    22  _name =
     name;
    23 }

    24
    25 public void setSex(String sex) 
    {
    26  _sex =
     sex;
    27 }

    28
    29 public String getName() 
    {
    30  return
     _name;
    31 }

    32
    33 public String getSex() 
    {
    34  return
     _sex;
    35 }

    36
    37}

    38

    Parent類
     1package xmlTest;
     2

     3import
     java.io.PrintWriter;
     4import
     java.lang.reflect.Array;
     5import java.util.*
    ;
     6

     7public class Parent extends JXmlSerializable 
    {
     8

     9    private
     String _name;
    10    private
     String _sex;
    11    private LinkedList list = new
     LinkedList();
    12    private Vector vec = new
     Vector();
    13    int
     age;
    14

    15    public void setAge(int num) 
    {
    16        age =
     num;
    17    }

    18
    19    public int getAge() 
    {
    20        return
     age;
    21    }

    22
    23    public void setName(String name) 
    {
    24        _name =
     name;
    25    }

    26
    27    public void setSex(String sex) 
    {
    28        _sex =
     sex;
    29    }

    30
    31    public String getName() 
    {
    32        return
     _name;
    33    }

    34
    35    public String getSex() 
    {
    36        return
     _sex;
    37    }

    38
    39    public void addChild(Child child) 
    {
    40
            list.add(child);
    41
            vec.add(child);
    42    }

    43
    44    public Child[] getChild() 
    {
    45

    46        Child[] aa = new
     Child[vec.size()];
    47        // list.toArray(aa);

    48        vec.toArray(aa);
    49        return
     aa;
    50    }

    51
    52    public static void main(String[] args) 
    {
    53        // TODO Auto-generated method stub

    54        try {
    55            Parent pat = new
     Parent();
    56            pat.setName("jack"
    );
    57            pat.setSex("male"
    );
    58            Child child1 = new
     Child();
    59            child1.setName("tom"
    );
    60            child1.setSex("male"
    );
    61
                pat.addChild(child1);
    62            Child child2 = new
     Child();
    63            child2.setName("Marie"
    );
    64            child2.setSex("female"
    );
    65
                pat.addChild(child2);
    66
                pat.getChild();
    67            PrintWriter out = new PrintWriter("abc.xml"
    );
    68            pat.toXmlSerial(out,0
    );
    69
                out.flush();
    70

    71        }
     catch (Exception e) {
    72
                e.printStackTrace();
    73        }

    74
    75    }

    76}

    類 JXmlSerializable
     1package xmlTest;
     2

     3import
     java.lang.reflect.Method;
     4import
     java.lang.reflect.InvocationTargetException;
     5import
     java.lang.reflect.Array;
     6import
     java.io.PrintWriter;
     7import
     java.io.IOException;
     8public class JXmlSerializable 
    {
     9

    10    public void toXmlSerial(PrintWriter out, int
     num)
    11            throws
     InvocationTargetException, IllegalAccessException,
    12            IOException 
    {
    13        out.write("<?xml version="1.0"?> "
    );
    14        String head = ""
    ;
    15        for (int i = 0; i < num; i++
    {
    16            head += " "
    ;
    17        }

    18        out.write(head + "<" + this.getClass().getName() + "");
    19        Method[] methods = this
    .getClass().getMethods();
    20        for (int i = 0; i < methods.length; i++
    {
    21            Class[] paras =
     methods[i].getParameterTypes();
    22            String name =
     methods[i].getName();
    23            if (paras == null || paras.length == 0
    {
    24                if ((name.substring(03).toLowerCase().equals("get"
    ))
    25                        && !name.equals("getClass")) 
    {
    26                    Object obj = methods[i].invoke(thisnull
    );
    27
                        getMethodXmlSerial(out, obj, methods[i], num);
    28                }

    29            }

    30        }

    31
    32        out.write(head + "</" + this.getClass().getName() + ""
    );
    33

    34    }

    35
    36    private void
     getMethodXmlSerial(PrintWriter out, Object obj, Method method,
    37            int num) throws
     InvocationTargetException, IllegalAccessException,
    38            IOException 
    {
    39        if (obj == null
    )
    40            return
    ;
    41        String head = ""
    ;
    42        for (int i = 0; i <= num; i++
    {
    43            head += " "
    ;
    44        }

    45        if (obj.getClass().isArray()) {
    46            for (int i = 0; i < Array.getLength(obj); i++
    {
    47                Object childobj =
     Array.get(obj, i);
    48                if (childobj instanceof JXmlSerializable) 
    {
    49                    ((JXmlSerializable) childobj).toXmlSerial(out, num + 1
    );
    50                }
     else {
    51
                        getMethodXmlSerial(out, childobj, method, num);
    52                }

    53            }

    54        }
     else {
    55            out.write(head + "   <" + method.getName().substring(3+ ">   "
    );
    56
                out.write(obj.toString());
    57            out.write("   </" + method.getName().substring(3+ ">    "
    );
    58        }

    59
    60    }

    61}

    編譯出來還可以,能夠達(dá)到我的理想。

    編譯結(jié)果是

     1<?xml version="1.0"?>
     2<xmlTest.Parent>
     3       <Name>   jack   </Name>   
     4       <Age>   0   </Age>
       
     5       <Sex>   male   </Sex>
       
     6<?xml version="1.0"?>

     7    <xmlTest.Child>
     8           <Name>   tom   </Name>   
     9           <Age>   0   </Age>
       
    10           <Sex>   male   </Sex>
       
    11    </xmlTest.Child>

    12<?xml version="1.0"?>
    13    <xmlTest.Child>
    14           <Name>   Marie   </Name>   
    15           <Age>   0   </Age>
       
    16           <Sex>   female   </Sex>
       
    17    </xmlTest.Child>

    18</xmlTest.Parent>

    今天看了看java.beans包,發(fā)現(xiàn)了兩個好東西,XMLEncoder和XMLDecoder。發(fā)現(xiàn)自己以前把從XML存取對象真是太費(fèi)力氣啦。做了小工具類,以后可以用用了。
     1以下是引用片段:
     2package
     com.imct.util; 
     3import
     java.beans.XMLDecoder; 
     4import
     java.beans.XMLEncoder; 
     5import
     java.io.File; 
     6import
     java.io.FileInputStream; 
     7import
     java.io.FileNotFoundException; 
     8import
     java.io.FileOutputStream; 
     9import
     java.io.IOException; 
    10import
     java.util.ArrayList; 
    11import
     java.util.List; 
    12
    /** 
    13
     * <title>使用XML文件存取可序列化的對象的類</title> 
    14
     * <description>提供保存和讀取的方法</description> 
    15 * @author
     殷晉 
    16
     * <copyright>清華大學(xué)汽車工程開發(fā)研究院@2005</copyright> 
    17 * @version
     1.0 
    18
     * 2005-8-5 16:44:49 
    19 */
     
    20public class
     ObjectToXMLUtil 
    21

    22 
    /** 
    23
      * 把java的可序列化的對象(實(shí)現(xiàn)Serializable接口)序列化保存到XML文件里面,如果想一次保存多個可序列化對象請用集合進(jìn)行封裝 
    24
      * 保存時將會用現(xiàn)在的對象原來的XML文件內(nèi)容 
    25  * @param
     obj 要序列化的可序列化的對象 
    26  * @param
     fileName 帶完全的保存路徑的文件名  
    27  * @throws
     FileNotFoundException 指定位置的文件不存在 
    28  * @throws
     IOException 輸出時發(fā)生異常 
    29  * @throws
     Exception 其他運(yùn)行時異常 
    30  */
     
    31 public static void
     objectXmlEncoder(Object obj,String fileName) 
    32  throws
     FileNotFoundException,IOException,Exception 
    33 
    {   
    34  //創(chuàng)建輸出文件 

    35  File fo = new File(fileName); 
    36  //文件不存在,就創(chuàng)建該文件 

    37  if(!fo.exists()) 
    38  

    39   //先創(chuàng)建文件的目錄 

    40      String path = fileName.substring(0,fileName.lastIndexOf('.')); 
    41      File pFile = new
     File(path); 
    42
          pFile.mkdirs();          
    43  }
     
    44  //創(chuàng)建文件輸出流 

    45  FileOutputStream fos = new FileOutputStream(fo); 
    46  //創(chuàng)建XML文件對象輸出類實(shí)例 

    47  XMLEncoder encoder = new XMLEncoder(fos);   
    48  //對象序列化輸出到XML文件 

    49  encoder.writeObject(obj); 
    50
      encoder.flush();  
    51  //關(guān)閉序列化工具 

    52  encoder.close(); 
    53  //關(guān)閉輸出流 

    54  fos.close();     
    55 }
      
    56 
    /** 
    57
      * 讀取由objSource指定的XML文件中的序列化保存的對象,返回的結(jié)果經(jīng)過了List封裝 
    58  * @param
     objSource 帶全部文件路徑的文件全名 
    59  * @return
     由XML文件里面保存的對象構(gòu)成的List列表(可能是一個或者多個的序列化保存的對象)   
    60  * @throws
     FileNotFoundException 指定的對象讀取資源不存在 
    61  * @throws
     IOException 讀取發(fā)生錯誤 
    62  * @throws
     Exception 其他運(yùn)行時異常發(fā)生 
    63  */
     
    64 public static
     List objectXmlDecoder(String objSource)  
    65  throws
     FileNotFoundException,IOException,Exception 
    66 

    67  List objList = new
     ArrayList();     
    68  File fin = new
     File(objSource); 
    69  FileInputStream fis = new
     FileInputStream(fin); 
    70  XMLDecoder decoder = new
     XMLDecoder(fis); 
    71  Object obj = null

    72  try
     
    73  

    74   while( (obj = decoder.readObject()) != null

    75   

    76
        objList.add(obj); 
    77   }
     
    78  }
     
    79  catch
     (Exception e) 
    80  

    81   // TODO Auto-generated catch block     

    82  }
     
    83
      fis.close(); 
    84
      decoder.close();      
    85  return
     objList; 
    86 }
     
    87}
     
    88
     
    89

    90
    當(dāng)然用Beans.instantiate也可以從文件中反序列化初對象
    91

    92
    posted on 2008-11-25 09:00 Vincent-chen 閱讀(487) 評論(0)  編輯  收藏 所屬分類: XML
    主站蜘蛛池模板: 苍井空亚洲精品AA片在线播放 | 亚洲国产一区二区三区| 中文字幕不卡亚洲 | 性xxxxx免费视频播放| 国产精品免费看久久久无码| 久久被窝电影亚洲爽爽爽 | 三年片免费高清版 | 我要看免费的毛片| 亚洲一区二区三区无码中文字幕| 亚洲欧洲日产国码在线观看| 老司机免费午夜精品视频| 亚洲免费网站在线观看| 亚洲AV无码AV吞精久久| 亚洲日本VA午夜在线电影| 免费无码一区二区三区蜜桃| 久久国产精品成人免费| 天天看片天天爽_免费播放| 亚洲精品无码av人在线观看| 亚洲精品无码久久久久秋霞| 日本一道本不卡免费| 亚洲精品国产精品国自产观看| 91亚洲国产成人久久精品| a级毛片免费观看网站| 成人无遮挡毛片免费看| 亚洲综合婷婷久久| 亚洲中文字幕无码mv| 永久在线观看免费视频| 亚洲 小说区 图片区 都市| 亚洲AV无码一区二区三区人| 在线观看免费播放av片| 又黄又爽的视频免费看| 亚洲精品乱码久久久久66| 亚洲国产美女精品久久久| 91精品免费观看| 国产一区二区三区免费在线观看| 亚洲视屏在线观看| 中文字幕在线视频免费| 国产免费牲交视频| 久久亚洲最大成人网4438| 69视频在线观看免费| 精品国产综合成人亚洲区 |