首页 > 解决方案 > Gson 流关闭

问题描述

当您使用以下内容时,流是否关闭:

gson.toJson(obj, new FileWriter("C:\\fileName.json"));

还是这样做更好:

        try (Reader reader = new FileReader("c:\\test\\staff.json")) {

            // Convert JSON File to Java Object
            Staff staff = gson.fromJson(reader, Staff.class);

            // print staff 
            System.out.println(staff);

        } catch (IOException e) {
            e.printStackTrace();
        }

我知道 try 块关闭了流,但是第一个示例是否也关闭了流?

取自 Mkyong的代码

标签: javajsonstreamgsoncoding-efficiency

解决方案


当您使用以下内容时,流是否关闭:

gson.toJson(obj, new FileWriter("C:\\fileName.json"));

它不是。您应该使用 try-with-resources 或 try-catch-finally 块来关闭它。


从 JDK 7 开始,关闭 AutoClosable 的首选方法是使用 try-with-resources (就像在您的第二个片段中一样):

try (FileWriter writer = new FileWriter("C:\\fileName.json")) {
    gson.toJson(obj, writer);
} catch (IOException e) {
    e.printStackTrace();
}

或者您可以close()使用 try-catch-finally 块调用:

FileWriter writer = null;
try {
    writer = new FileWriter("C:\\fileName.json");
    gson.toJson(obj, writer);
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (writer != null) {
        try {
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

推荐阅读