Serializing Java Objects as XML - Java File Path IO

Java examples for File Path IO:Serialization

Introduction

XMLEncoder can encode the object.

Demo Code

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");
    try {// ww  w  .  j a  va2s  . c  om
      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 void readExternal(ObjectInput in) throws IOException,
      ClassNotFoundException {
    title = in.readUTF();
  }

  public MyClass(String title) {
    this.title = title;
  }

  public String getTitle() {
    return title;
  }

  public void setTitle(String title) {
    this.title = title;
  }
}

Related Tutorials