集册 Java实例教程 将Java对象序列化为XML

将Java对象序列化为XML

欢马劈雪     最近更新时间:2020-01-02 10:19:05

565
XMLEncoder可以对对象进行编码。
//来自 NowJava.com - 时  代  Java

import java.beans.XMLDecoder;

import java.beans.XMLEncoder;

import java.io.Externalizable;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInput;

import java.io.ObjectOutput;

import java.nio.charset.Charset;

import java.nio.file.FileSystem;

import java.nio.file.FileSystems;

import java.nio.file.Files;

import java.nio.file.Path;

import java.util.List;


public class Main {

  public static void main(String[] args) {

    MyClass settings = new MyClass("The title of the application");//来自 时代Java公众号

    try {

      FileSystem fileSystem = FileSystems.getDefault();

      try (FileOutputStream fos = new FileOutputStream("settings.xml");

          XMLEncoder encoder = new XMLEncoder(fos)) {

        encoder.setExceptionListener((Exception e) -> {

          System.out.println("Exception! :" + e.toString());

        });

        encoder.writeObject(settings);

      }

      try (FileInputStream fis = new FileInputStream("settings.xml");

          XMLDecoder decoder = new XMLDecoder(fis)) {

        MyClass decodedSettings = (MyClass) decoder.readObject();

        System.out.println("Is same? " + settings.equals(decodedSettings));

      }


      Path file = fileSystem.getPath("settings.xml");

      List<String> xmlLines = Files

          .readAllLines(file, Charset.defaultCharset());

      xmlLines.stream().forEach((line) -> {

        System.out.println(line);

      });


    } catch (IOException e) {

      e.printStackTrace();

    }

  }

}


class MyClass implements Externalizable {

  private String title;


  public MyClass() {

  }


  @Override

  public void writeExternal(ObjectOutput out) throws IOException {

    out.writeUTF(title);

  }


  @Override

  public 
展开阅读全文