How to store object implementing org.apache.geode.pdx.PdxSerializable in file in java

KCK :

I have a class implementing org.apache.geode.pdx.PdxSerializable and need to store the objects of it in file in java. For sotring in file, the object needs to be Serializable but the class PDXSerializable is being used for storing data in gemfire and hence we cannot use Serializable class.

Laksitha Ranasingha :

Why don't you use custom object serialization?. Here's an example that I have quickly created;


 private class Foo implements PdxSerializable {
        private String bar;
        private Integer baz;

        public Foo(final String bar, final Integer baz) {

            this.bar = bar;
            this.baz = baz;
        }

        public String getBar() {
            return bar;
        }

        public Integer getBaz() {
            return baz;
        }
        public void toData(PdxWriter out) {
         //your pdx stuff
        }

        public void fromData(PdxReader in) {
          //your pdx work
        }
    }

//and a custom reader and writer 
     private void writeCustom(final Foo foo, final Path path) throws IOException {
        try(ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(path.toFile()))) {
            objectOutputStream.writeChars(foo.getBar());
            objectOutputStream.writeInt(foo.getBaz());
        }
    }

    private Foo readCustom(final Path path) throws IOException {
        try(ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(path.toFile()))) {
            String bar = objectInputStream.readUTF();
            Integer baz = objectInputStream.readInt();
            return new Foo(bar, baz);
        }
    }

Custom Serialization Oracle docs - https://www.oracle.com/technetwork/articles/java/javaserial-1536170.html

A similar question with great answers - Java Custom Serialization

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=94534&siteId=1