【问题标题】:Is there an easy way to save arraylist/variables data to a file in Java? [duplicate]有没有一种简单的方法可以将数组列表/变量数据保存到 Java 文件中? [复制]
【发布时间】:2013-11-25 19:12:00
【问题描述】:

我有一个自定义类型的数组列表。在 C 中,我可以找出数组或变量在内存中的存储位置,然后将这部分内存保存到文件中,然后再次将其直接加载到数组/变量中。

我将如何在 Java 中执行此操作,有简单的方法吗?

【问题讨论】:

  • 去阅读java序列化。
  • 我是implements SerializableGson的粉丝

标签: java file-io arraylist


【解决方案1】:

关键字是序列化。 List 中的元素需要实现Serializable 接口,该类中的所有元素也是如此。

static class Baz implements Serializable {
    private static final long   serialVersionUID    = 1L;
    int i;
    String s;
    public Baz(int i, String s) { this.i = i; this.s = s; }
}

@Test
public void serAL() throws FileNotFoundException, IOException, ClassNotFoundException {
    List<Baz> list = Arrays.asList(new Baz(1, "one"), new Baz(2, "two"), new Baz(3, "three"));
    try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("al.dat"))) {
        oos.writeObject(list);
    }
    try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("al.dat"))) {
        @SuppressWarnings("unchecked")
        List<Baz> serAL = (List<Baz>) ois.readObject();
        Assert.assertEquals(3, serAL.size());
        Assert.assertEquals(1, serAL.get(0).i);
        Assert.assertEquals("one", serAL.get(0).s);
        Assert.assertEquals(2, serAL.get(1).i);
        Assert.assertEquals("two", serAL.get(1).s);
        Assert.assertEquals(3, serAL.get(2).i);
        Assert.assertEquals("three", serAL.get(2).s);
    }
}

【讨论】:

    【解决方案2】:

    一个使用Kryobenchmark的例子:

    static class Foo{
        String name;
    
        Foo() {
        }
    
        Foo(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("Foo{");
            sb.append("name='").append(name).append('\'');
            sb.append('}');
            return sb.toString();
        }
    }
    
    public static void main(String[] args) {
        Kryo kryo = new Kryo();
    
        Output output = new Output(100);
    
        List<Foo> foos = Arrays.asList(new Foo("foo1"), new Foo("foo2"), new Foo("foo3"));
    
        kryo.writeObject(output, foos.subList(1, 3));
    
        List<Foo> foosAfter = kryo.readObject(new Input(output.toBytes()), ArrayList.class);
    
        System.out.println("before: " + foos);
        System.out.println("after: " + foosAfter);
        System.out.println("bytes: " + Arrays.toString(output.toBytes()));
    }
    

    输出:

    before: [Foo{name='foo1'}, Foo{name='foo2'}, Foo{name='foo3'}]
    after: [Foo{name='foo2'}, Foo{name='foo3'}]
    bytes: [1, 2, 1, 0, 99, 104, 97, 115, 99, 104, 101, 118, 46, 117, 116 ...
    

    【讨论】:

      猜你喜欢
      • 2011-02-17
      • 2021-03-05
      • 1970-01-01
      • 2013-03-26
      • 2016-08-13
      • 2011-01-03
      • 1970-01-01
      • 2019-10-16
      • 2021-01-09
      相关资源
      最近更新 更多