FileReader,如果不存在则创建文件

时间:2015-10-22 18:22:43

标签: java json filereader

我正在编写一个方法,假设将新电影添加到我的JSON列表中。它必须附加到现有列表,如果有的话。如果文件不存在,则创建一个JSON文件。

我正在使用org.json.simple library

我现在的问题是,如果文件不存在,它将无法正常工作。我如何检查我是否是第一次写它并因此管理它?

    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();
    }
}

示例JSON数据:

{
   "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"
      }
   ]
  }

2 个答案:

答案 0 :(得分: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?

答案 1 :(得分:0)

您在问题中已提到如果该文件不存在,则此代码将无效。好吧,如果它不存在,那么这就是你如何创建它。

'&l'