有没有一种简单的方法可以将arraylist / variables数据保存到Java中的文件中?

时间:2013-11-25 19:12:01

标签: java file-io arraylist

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

我如何在Java中实现这一点,有一种简单的方法吗?

2 个答案:

答案 0 :(得分:0)

关键字是序列化。 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);
    }
}

答案 1 :(得分:0)

使用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 ...