我正在使用 Serializable 从文件中读取对象:
public ArrayList<Object> deserialzePerson(String filename) {
Object obj = null;
ObjectInputStream ois;
try {
ois = new ObjectInputStream(new FileInputStream(filename));
for (int i = 0; i < 100; i++) {
obj = (Object) ois.readObject();
ObjectArray.add(obj);
}
} catch (Exception e) {
}
return ObjectArray;
}
但是,我不知道文件中的对象数量,因此在 for 循环中使用了数字“100”。如果少于 100,异常将启动并且一切都按预期进行。尽管如此,我发现这个解决方案很差,因为它依赖于捕获错误。有没有办法为文件中的对象数量设置 for 循环的限制?
例如,当我使用 .hasNext();
读取 .txt 文件时,是否有类似这样的对象?
最佳答案
public void serializePerson(String filename, List<Person> persons) {
try (FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream ous = new ObjectOutputStream(fos)) {
ous.writeInt(persons.size());
for (Person person : persons) {
ous.writeObject(person);
}
} catch (Exception e) {
}
}
public List<Person> deserializePerson(String filename) {
List<Person> result = new ArrayList<>();
try (FileInputStream fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis)) {
int size = ois.readInt();
for (int i = 0; i < size; i++) {
Person person = (Person) ois.readObject();
result.add(person);
}
} catch (Exception e) {
}
return result;
}
关于java - 从文件中知道可序列化对象的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42053323/