Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reading File not reading properly

I feel like I’m making a dumb mistake because I’ve been able to do this successfully before, I’m trying to read a file to an Object ArrayList, here’s the method.

public static void readFile (String fileName, ArrayList <Pokemon> newPokedex) {
    try{
        FileInputStream readData = new FileInputStream(fileName);
        ObjectInputStream readStream = new ObjectInputStream(readData);
        newPokedex = (ArrayList<Pokemon>) readStream.readObject();
        readStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

It’ll work if I don’t add parameters, but every time I do, it tells me my ArrayList is empty.

public static void main (String [] args) {
    Pokemon.readFile("Pokedex.txt", Pokemon.Pokedex);
    System.out.println(Pokedex.size());
}

My write method works just fine and it’ll also print the correct size when I tell it to print it in the method

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your error lies in the way you are using the

ArrayList <Pokemon> newPokedex

parameter.

In this line:

newPokedex = (ArrayList<Pokemon>) readStream.readObject();

you are not reading into the list that you provided as a parameter, instead you are overriding the list reference where the parameter is pointing. But that does not change the list reference outside your method. This is a common mistake.

If you use this line of code instead of the original, it should work:

newPokedex.addAll((ArrayList<Pokemon>) readStream.readObject());

Now you are actually adding all the items from the list that you read from the file into the list that you have provided as a parameter.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading