[英]Reading line by line in a serialized file
I have a serialized file and I'm trying to grab each line in it and add that into a LinkedList. 我有一个序列化的文件,我试图抓住其中的每一行并将其添加到LinkedList中。 Can I do this using the Scanner
or since its serialized do I have to you ObjectInputStream
? 我可以使用Scanner
做到这一点吗,或者由于它已经序列化了,所以我需要ObjectInputStream
吗? I assume with the scanner you could use scanner.nextLine() or something similar but I don't think the OOS has something like that? 我认为使用扫描仪可以使用scanner.nextLine()或类似的东西,但是我不认为OOS有这样的东西吗? How would I go about adding each line to a seperate node in the list? 如何将每行添加到列表中的单独节点?
This question is also tied to this question here . 这个问题在这里也与此问题联系在一起。 This is how the tree is originally serialized. 这是树最初被序列化的方式。
There are no new lines in a serialized file (unless you somehow make it that way when you originally write it). 序列化文件中没有新行(除非您在最初编写它时以某种方式创建了它)。 You will have to use ObjectOutputStream
and ObjectInputStream
to serialize and deserialize. 您将必须使用ObjectOutputStream
和ObjectInputStream
进行序列化和反序列化。 If you are serializing a bunch of objects your best option would probably be to serialize the entire list, and then deserialize the whole thing at once again, and add it back to a new list. 如果要序列化一堆对象,最好的选择可能是序列化整个列表,然后再次反序列化整个对象 ,然后将其添加回新列表。 Judging by your other question, a good option might be to add each node into a list rather than writing each object to file separately: 从另一个问题来看,一个不错的选择可能是将每个节点添加到列表中,而不是将每个对象分别写入文件中:
...
if (focusNode != null){
System.out.println(focusNode);
list.add(focusNode);
preOrderTraverseTree(focusNode.leftChild);
preOrderTraverseTree(focusNode.rightChild);
}//end if
...
and then to save it: 然后保存:
try (ObjectOutputStream output = new ObjectOutputStream(
new FileOutputStream(file))) {
output.writeObject(lList);//this will write the list as a whole to the file
}
and to read it back, I would suggest putting it back into the list: 并读回去,我建议将其放回列表中:
try (ObjectInputStream input = new ObjectInputStream(
new FileInputStream(file))) {
newList = (List) input.readObject();
from there, if you need to use the objects again, you can pull them out of the list, etc. 从那里开始,如果您需要再次使用这些对象,则可以将它们从列表中拉出,等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.