我有一个对象数组,我想将它们写入文本文件中。这样我以后就可以将对象读回到数组中。我该怎么做呢?使用序列化。
反序列化不起作用:
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();
}
将对象转换为字符串以及反之亦然的过程称为序列化和反序列化。为了序列化一个对象,它应该实现Serializable
界面。大多数内置数据类型和数据结构默认都是可序列化的,只有某些类不可序列化(例如Socket
不可序列化)。
所以首先你应该让你的类可序列化:
class Student implements java.io.Serializable {
String name;
String studentId;
float gpa;
transient String thisFieldWontBeSerialized;
}
您可以使用ObjectOutputStream
将其序列化并写入文件:
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
可以以类似的方式从文件中读回数组。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)