0

I have an arraylist of a custom type. In C I could figure out where the array or variable was stored in memory then just save that part of memory to a file, then load it again directly into the array/variable.

How would I go about doing this in Java, is there an easy way?

Liftoff
  • 24,717
  • 13
  • 66
  • 119
rambodash
  • 87
  • 1
  • 7

2 Answers2

0

The keyword is serialization. The elements in your List need to implement the Serializable interface, also all the elements in that class.

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);
    }
}
A4L
  • 17,353
  • 6
  • 49
  • 70
0

An example using Kryo, benchmark:

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

Output:

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 ...
Andrey Chaschev
  • 16,160
  • 5
  • 51
  • 68