使用Gson序列化Student对象时输出JSON文件为空的问题求助
问题根因
- 写入文件的字符流
FileWriter使用后未关闭,也未主动刷写缓冲区:带缓冲的字符输出流默认会将写入内容暂存在JVM内存缓冲区,只有缓冲区满、主动调用flush()、主动调用close()时才会将内容同步到磁盘。当前代码写入完成后直接结束程序,缓冲区内容还没来得及写入磁盘,所以生成的文件为空。
修复方案
方案1(推荐):使用Java 7+支持的try-with-resources语法,会自动完成流的关闭、刷写操作,不需要手动处理:
String sFileName = "student.json"; // 把Writer定义在try后的括号内,代码块执行完自动关闭流 try(Writer writer = new FileWriter(sFileName)){ gson.toJson(student, writer); } catch(IOException ex){ System.out.println (ex.toString()); System.out.println("Could not find file " + sFileName); }
你注释掉的Files.newBufferedWriter写法同样适用上述逻辑,放到try-with-resources括号内即可自动关闭资源。
方案2:写入完成后手动调用flush()刷写+close()关闭流:
String sFileName = "student.json"; Writer writer = null; try{ writer = new FileWriter(sFileName); gson.toJson(student, writer); writer.flush(); // 手动刷写缓冲区内容到磁盘 } catch(IOException ex){ System.out.println (ex.toString()); System.out.println("Could not find file " + sFileName); } finally { // finally块保证无论是否抛出异常都能关闭流 if(writer != null){ try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
内容的提问来源于stack exchange,提问作者Bussiere
相关产品推荐
相关产品推荐

