I have a StorageImpl class which is serializable. This class has an inner class Record.
public class StorageImpl <ID, T extends IDataStore<ID>> implements IStorage <T, ID>
{
private class Record implements Serializable
{
private static final long serialVersionUID = 1L;
private Long key;
private List<T> dataList;
private Record()
{
key = new Long(0);
dataList = new ArrayList<T>();
}
}
}
I want to store and retrieve a Record which in turn has
private Long key;
private List<T> dataList;
Once I retrieve a Record, I can get all the books in bookList member of the Record.
public class StorageImpl <ID, T extends IDataStore<ID>> implements IStorage <T, ID>
{
private class Record implements Serializable
{
private static final long serialVersionUID = 1L;
private Long key;
private List<T> dataList;
private Record()
{
key = new Long(0);
dataList = new ArrayList<T>();
}
private String dataFile;
private Record record;
public StorageImpl(String dataFile)
{
this.dataFile = dataFile;
record = new Record();
}
public List<T> retrieve() throws Exception
{
List<T> dataList = new ArrayList<>();
File file = new File(dataFile);
if (!file.exists())
{
return dataList;
}
try (FileInputStream fis = new FileInputStream(dataFile); ObjectInputStream ois = new ObjectInputStream(fis))
{
record = (Record) ois.readObject();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
for (int i = 0; i < record.dataList.size(); i++)
{
dataList.add(record.dataList.get(i));
}
return dataList;
}
@SuppressWarnings("unchecked")
@Override
public void store(T t) throws Exception
{
List<T> dataList = retrieve();
++record.key;
t.setID((ID) record.key);
dataList.add(t);
record.dataList = dataList;
writeData(record);
}
private void writeData(Record record)
{
try (FileOutputStream fos = new FileOutputStream(dataFile);
ObjectOutputStream oos = new ObjectOutputStream(fos))
{
oos.writeObject(record);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Update:
Please note I want to persist just a Record and not a List.
The error after code changes looks like relates to Record not being serializable:
Caused by: java.io.NotSerializableException:
atjava.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at StorageImpl.writeData(StorageImpl..java:159)
And this is the call inside writeData() at line 159
oos.writeObject(record);