[英]how to write/read multiple object arrays using a text file [Java]
[英]How to read and write an object to a text file in java?
我有一个对象数组,我想在文本文件中写它们。 这样我以后就可以在数组中读回对象了。 我该怎么办? 使用序列化。
反序列化不起作用:
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
不可序列化)。
首先,你应该使你的类Serializable:
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
从文件中读取数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.