XMLEncoder和XMLDecoder 类使用示例

//转帖引用 : http://rogershi.blogbus.com/logs/355406.html


import net.zukowski.ibm.Sample;
import java.io.*;
import java.beans.*;
import java.awt.Point;

public class SampleTest {
    public static void main(String args[]) throws Exception {
        Sample sample = new Sample();
        sample.setScores(new int[] { 100, 90, 75 });
        sample.setName("Gore");
        sample.setSeat(new Point(5, 3));

        XMLEncoder encoder =
            new XMLEncoder(
                new BufferedOutputStream(new FileOutputStream("Sample.xml")));
        encoder.writeObject(sample);
        encoder.close();

        System.out.println(sample);

        XMLDecoder decoder =
            new XMLDecoder(
                new BufferedInputStream(new FileInputStream("Sample.xml")));
        Sample sample2 = (Sample) decoder.readObject();
        decoder.close();

        System.out.println(sample2);

    }
}

// Sample.xml
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.4.2_02" class="java.beans.XMLDecoder">
    <object class="rrrtest.Sample">
        <void property="name">
            <string>Gore</string>
        </void>
        <void property="scores">
            <array class="int" length="3">
                <void index="0">
                    <int>100</int>
                </void>
                <void index="1">
                    <int>90</int>
                </void>
                <void index="2">
                    <int>75</int>
                </void>
            </array>
        </void>
        <void property="seat">
            <object class="java.awt.Point">
                <int>5</int>
                <int>3</int>
            </object>
        </void>
    </object>
</java>

// Sample.java

import java.awt.Point;
public class Sample {
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public int[] getScores() {
        return scores;
    }

    public void setScores(int[] scores) {
        this.scores = scores;
    }

    public Point getSeat() {
        return seat;
    }

    public void setSeat(Point seat) {
        this.seat = seat;
    }
    private int[] scores;
    private String name;
    private Point seat;
}

你可能感兴趣的:(java,html,xml,.net,IBM)