如何从ObjectInputStream读取所有对象 [英] How to read all objects from ObjectInputStream
问题描述
我有一个包含一些信息的文件,如何读取所有信息?
I have a file with some info how can I read all info?
Name names;
try (FileInputStream fileInputStream = new FileInputStream(file)) {
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
names = (Name) objectInputStream.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
推荐答案
您有几种解决方案,具体取决于输入内容:
You have several solution, all depending on the input:
-
您可以迭代直到流被完全用尽:我认为这是我提供给您的解决方案中最糟糕的解决方案.更糟糕的是,您正在检查是否已达到EOF,同时您应该知道完成的时间(例如:文件格式错误).
You can iterate until the stream is fully consumed: I think that is the worse solution out of those I provide you. It is worse because you are checking if EOF was reached, whilst you should know when you're done (eg: your file format is wrong).
Set<Name> result = new HashSet<>();
try {
for (;;) {
result.add((Name)objectInputStream.readObject());
}
} catch (EOFException e) {
// End of stream
}
return result;
产生输入时,序列化一个集合并在其上调用 readObject()
.只要每个对象都实现了 Serializable
.
When producing the input, serialize a collection and invoke readObject()
on it. Serialization
should be able to read the collection, as long as each object implements Serializable
.
static void write(Path path, Set<Name> names) throws IOException {
try (OutputStream os = Files.newOutputStream(path);
ObjectOutputStream oos = new ObjectOutputStream(os)) {
oos.writeObject(names);
}
}
static Set<Name> read(Path path) throws IOException {
try (InputStream is = Files.newInputStream(path);
ObjectInputStream ois = new ObjectInputStream(is)) {
// WARN Files.newInputStream is not buffered; ObjectInputStream might
// be buffered (I don't remember).
return (Set<Name>) ois.readObject();
}
}
在生成输入时,可以添加一个 int
来指示要读取的对象的数量,并对其进行迭代:如果您真的不在乎该对象,这很有用.集合( HashSet
).生成的文件将较小(因为您将没有 HashSet
元数据).
When producing the input, you can add a int
indicating the number of object to read, and iterate over it: this is useful in case where you don't really care of the collection (HashSet
). The resulting file will be smaller (because you won't have the HashSet
metadata).
int result = objectInputStream.readInt();
Name[] names = new Name[result]; // do some check on result!
for (int i = 0; i < result; ++i) {
names[i] = (Name) objectInputStream.readObject();
}
此外, Set
很好,但是由于它们使用 hashCode()
/ equals()
删除重复项,如果您的事实之后,等于
/ hashCode
的定义发生了变化(例如:您的名称
区分大小写,现在则不区分大小写,例如: new名称("AA").等于(新名称("aa"))
).
Also, Set
are good, but since they remove duplicate using hashCode()
/equals()
you may get less object if your definition of equals
/hashCode
changed after the fact (example: your Name
was case sensitive and now it is not, eg: new Name("AA").equals(new Name("aa"))
).
这篇关于如何从ObjectInputStream读取所有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!