问题
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();
}
回答1:
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.
回答2:
As far as I know, Java doesn't give you an easy way to do this for arbitrary objects. Thus, consider restricting yourself to an array of Serializable
.
If the objects you have to handle are of your own classes and you thus want these classes to implement the java.io.Serializable
interface, carefully read what 'contract' it comes with, as not all of what you have to guarantee for your class will be enforced programatically at compile-time. (So if your classes implement Serializable
without completely following the conditions it poses, you might get runtime errors or just 'wrong' and maybe hard-to-detect runtime behavior.)
(See also these best practices.)
来源:https://stackoverflow.com/questions/30413227/how-to-read-and-write-an-object-to-a-text-file-in-java