I am writing a method which is suppose to add new movie to my JSON list. It has to append to existing list, if any. Or create a JSON file if the file does not exist.
I am using org.json.simple library
The issue I have now is, if the file does not exist, it would not work. How do I check whether am I writing it the first time and therefore manage it accordingly?
    public void insertMovie()
{
    Scanner myScanner = new Scanner(System.in);
    String movieTitle, movieType, director;
    System.out.println("Input the following");
    System.out.println("Movie Title: ");
    movieTitle = myScanner.next();
    System.out.println("Movie type: ");
    movieType = myScanner.next();
    System.out.println("Director's name: ");
    director = myScanner.next();
    JSONParser parser=new JSONParser();
    try{
        Object obj = parser.parse(new FileReader("./Database/Movies.json"));
        JSONObject currentObject = (JSONObject) obj;
        JSONArray movieArray = (JSONArray) currentObject.get("Movies");
        JSONObject newObject = new JSONObject();
        newObject.put("title", movieTitle);
        newObject.put("type", movieType);
        newObject.put("director", director);
        movieArray.add(newObject);
        FileWriter file = new FileWriter("./Database/Movies.json");
        file.write(movieArray.toJSONString());
        file.flush();
        file.close();
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }   
    catch (IOException e) {
        e.printStackTrace();
    }   
    catch (ParseException e) {
        e.printStackTrace();
    }
}
Sample JSON data:
{
   "Movies":[  
      {  
         "director":"director1",
         "title":"title1",
         "type":"type1"
      },
      {  
         "director":"director2",
         "title":"title2",
         "type":"type2"
      },
      {  
         "director":"director3",
         "title":"title3",
         "type":"type3"
      },
      {  
         "director":"lol3",
         "title":"lol1",
         "type":"lol2"
      }
   ]
  }
 
     
     
     
    