Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 376
KCK Avatar asked Apr 21 '26 23:04

KCK


1 Answers

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

like image 90
Laksitha Ranasingha Avatar answered Apr 24 '26 21:04

Laksitha Ranasingha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!