Gson流关闭

Gson stream closing

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

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

FileWriter 实现了 AutoClosable 所以它需要关闭。不命名变量不会自动关闭。

Does the stream close when you use something like:

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

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

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