我正在使用Java Eclipse创建一个事件管理系统,它将编写和读取JSON文件。这里我有代码创建一个新的JSON文件...
public void actionPerformed(ActionEvent arg0) {
//Declaration of variables
String title = txtTitle.getText();
String month = (String) cboMonth.getSelectedItem();
String day = (String) cboDate.getSelectedItem();
String year = (String) cboYear.getSelectedItem();
String location = txtLocation.getText();
String description = txtDescription.getText();
String URL = txtURL.getText();
// Combine multiple variables together to make a single variable
String date = month + "" + day + "" + year;
// Create a new instance of the class called 'Event'
Event event = new Event();
// Assign values to the getter/setter methods of this instance
event.setName(title);
event.setDate(date);
event.setLocation(location);
event.setDesc(description);
event.setURL(URL);
// Add this new instance to the 'eventList' array list
MainMenu.eventList.add(event);
// Create a new instance of the class called 'Event'
JSONObject JSONEvent = new JSONObject();
// Add data to the JSON file
JSONEvent.put("Title", title);
JSONEvent.put("Date", date);
JSONEvent.put("Location", location);
JSONEvent.put("Description", description);
JSONEvent.put("URL", URL);
// Create a new JSON file called 'Events.json' that has elements added to it
try (FileWriter file = new FileWriter("Events.json", true)) {
file.write("\n");
file.write(JSONEvent.toJSONString());
file.flush();
// Error Handling
} catch (IOException e) {
e.printStackTrace();
}
}
通过创建JSON文件并使用JSONObjects填充它,此代码可以正常工作。这是JSON文件中单个条目的图像...... Single JSON Element
然后我有一个单独的类,下面的代码试图读取JSON文件并将其内容输出到控制台...
public static void main(String[] args) {
JSONObject JSONEvent;
String line = null;
try {
FileReader fileReader = new FileReader("Events.json");
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
JSONEvent = (JSONObject) new JSONParser().parse(line);
String title = (String) JSONEvent.get("Title");
System.out.println(title);
String date = (String) JSONEvent.get("Date");
System.out.println(date);
String location = (String) JSONEvent.get("Location");
System.out.println(location);
String description = (String) JSONEvent.get("Description");
System.out.println(description);
String URL = (String) JSONEvent.get("URL");
System.out.println(URL);
Event event = new Event();
event.setName(title);
event.setDate(date);
event.setLocation(location);
event.setDesc(description);
event.setURL(URL);
MainMenu.eventList.add(event);
}
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
当我运行此代码时,我在控制台中得到以下错误... Unexpected token END OF FILE at position 0
有谁知道这个错误意味着什么?
你写入文件的第一件事是空行:
file.write("\n");
因此,在读取文件时,您尝试将空字符串解析为JSON,因此例外:解析器在有机会解析任何内容之前找到其输入的结尾。
而不是依赖于生成的JSON的内部格式,并将几个不同的JSON对象写入文件,在文件中一次编写单个对象数组(替换其先前的内容)会更简单,更安全,并在内存中一次读取整个数组。