Is there a way to write a method in Java that can load a file created by my "saveClassData"-Method" and return an array of the type the saved objects are of?
I've already tried out different ideas, but none of them worked. One problem was, that I wanted to give back an array of the specific object type, not of the type "object".
So I'm actually looking for method I could write with:
ObjectType[] array = loadClassData("classname", "fileLocation.csv");
Here's the code I wrote to save the object-data in a csv-document:
void saveClassData(String fileLocation, Object[]objects) {
try {
String[] data = new String[objects.length];
Class cls = objects[0].getClass();
Field[] fieldlist = cls.getDeclaredFields();
for (int i = 0; i < objects.length; i++) {
data[i] = "";
for (int t = 0; t < fieldlist.length-1; t++) {
Field fld = fieldlist[t];
data[i] += fld.get(objects[i]) + ",";
}
data[i] = data[i].substring(0, data[i].length()-1);
}
saveStrings(fileLocation, data);
}
catch (Throwable e) {
System.err.println(e);
}
}
It sounds like you're looking for serialization. Serialization allows you to write objects to a file and then read them from that file.
Here's a small example:
// write data
FileOutputStream fos = new FileOutputStream("YourFile.whatever");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(yourArray);
// read data
FileInputStream fis = new FileInputStream("YourFile.whatever");
ObjectInputStream iis = new ObjectInputStream(fis);
YourObject[] yourArray = (YourObject[]) iis.readObject();
Note that these files are not meant to be human readable or editable, and this will only work if every object in your data is serializable.
Google "java serialization" for a ton of results.
If serialization doesn't work for you, then you're probably stuck writing and reading the data yourself manually. Note that you can easily write the class to the file and create a new instance of that class based on the saved data.