简体   繁体   中英

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. Can I do this using the Scanner or since its serialized do I have to you 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? 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM