I have an array of objects and I want to write them in a text file. So that I can later read the objects back in an array. How should I do it? Using Serialization.
Deserialization is not working:
public static void readdata(){
ObjectInputStream input = null;
try {
input = new ObjectInputStream(new FileInputStream("myfile.txt")); // getting end of file exception here
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
array = (players[]) input.readObject(); // null pointer exception here
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
readdata();
writedata();
}
The process of converting objects into strings and vice versa is called Serialization and Deserialization. In order to serialize an object it should implement Serializable
interface. Most built-in data types and data structures are serializable by default, only certain classes are not serializable (for example Socket
is not serializable).
So first of all you should make your class Serializable:
class Student implements java.io.Serializable {
String name;
String studentId;
float gpa;
transient String thisFieldWontBeSerialized;
}
The you can use ObjectOutputStream
to serialize it and write to a file:
public class Writer {
static void writeToFile(String fileName, Student[] students) throws IOException {
File f = new File(fileName);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
oos.writeObject(students);
oos.flush();
oos.close();
}
}
ObjectInputStream
can be used in a similar way to read the array back from file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With