1

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"
      }
   ]
  }
Roman C
  • 49,761
  • 33
  • 66
  • 176
Gavin
  • 2,784
  • 6
  • 41
  • 78

2 Answers2

1
File f = new File("./Database/Movies.json");
if(f.exists() && !f.isDirectory())
    //write your json file

How do I check if a file exists in Java?

Community
  • 1
  • 1
phflack
  • 2,729
  • 1
  • 9
  • 21
0

You have mentioned in the question that this code will not work if the file does not exist. Well if it does not exist then here is how you can create it.

File yourFile = new File("./Database/Movies.json");

if(!yourFile.exists()) {
    yourFile.createNewFile(); //creating it
}

else if(yourFile.exists() && !yourFile.isDirectory()) {
    //append it
}
Riddhesh Sanghvi
  • 1,218
  • 1
  • 12
  • 22