首页 > 解决方案 > 如何在java中的文件中存储实现org.apache.geode.pdx.PdxSerializable的对象

问题描述

我有一个实现类org.apache.geode.pdx.PdxSerializable,需要将它的对象存储在 java 的文件中。为了存储在文件中,对象需要是,Serializable但是 PDXSerializable 类被用于在 gemfire 中存储数据,因此我们不能使用 Serializable 类。

标签: javajava-8niogeode

解决方案


为什么不使用自定义对象序列化?这是我快速创建的一个示例;


 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);
        }
    }

自定义序列化 Oracle 文档 - https://www.oracle.com/technetwork/articles/java/javaserial-1536170.html

一个类似的问题,答案很好 - Java Custom Serialization


推荐阅读