Home > other >  How could I read from an empty json File,at the start of the program is it empty but later can be wr
How could I read from an empty json File,at the start of the program is it empty but later can be wr

Time:12-09

The read file is that:

public ArrayList<Aventura> readFile(){
    ArrayList<Aventura> aventures = new ArrayList<>();
    try{
        AventuraDAO aventuraDAO=new AventuraDAO();
        AventuraManage aventuraManage=new AventuraManage(aventuraDAO);
        Gson g=new Gson();
        JsonReader reader=new JsonReader(new FileReader("Files/adventures.json"));
        Aventura[] ave=g.fromJson(reader, Aventura[].class );

        if (ave.length==0){
            System.out.println("The file should be empty");
            ArrayList<Aventura> aventures2 =null;
            return aventures2;
        }
        
        for (int i = 0; i < ave.length; i  ) {
            aventures.add(ave[i]);
        }
    }
    catch(FileNotFoundException e){
        System.out.println("The file does not exists");
    }
    catch (IOException e){
        ArrayList<Aventura> aventures2 =null;

        System.out.println(e.getMessage());
        e.printStackTrace();

    }
    return aventures;

I am trying to know if the object that is going to be read has a length==0 but that's not the way I suppose.Then I would return a null arraylist to in the future make some verifications.

I has:

Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "ave" is null
    at Persistence.AventuraDAO.readFile(AventuraDAO.java:25)
    at Business.AventuraManage.lookMonstersCombatActual(AventuraManage.java:48)
    at Presentation.Controller.createAdvenutre(Controller.java:198)
    at Presentation.Controller.executeOption(Controller.java:47)
    at Presentation.Controller.run(Controller.java:30)
    at Main.main(Main.java:21)

CodePudding user response:

try seperating into different values like

fileR = new FileReader("Files/adventures.json")
if fileR.length = 0 {return}
else
jsonR = new JsonReader(fileR)

CodePudding user response:

Your exception points to the variable "ave" being null, so do a null check on it to handle it being null.

This could be as simple as:

if (ave == null || ave.length==0){

Since the for loop assumes that there are values in the "ave" variable, you should put that in an else condition. That way the above if statement is the only thing you need to do to handle "ave" being null.

If you really do want to return a null from this method, then separate out the null check on it's own before your current if statement and return a null value there, since your default return value is an empty array. However, this also means you have to make sure your return datatype is nullable and you handle nulls in the code that uses the return value. This isn't hard, it's just something you have to keep in mind and remember to deal with.

if (ave == null){
  return null;
}
  • Related