简体   繁体   English

Gson 流关闭

[英]Gson stream closing

Does the stream close when you use something like:当您使用以下内容时,流是否关闭:

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

or is it better to to this:或者最好这样做:

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

I know the try block closes the stream, but does ths first example also close the stream?我知道 try 块会关闭流,但是第一个示例是否也关闭了流?

Code taken from Mkyong代码取自Mkyong

FileWriter implements AutoClosable so it needs to be closed. FileWriter实现AutoClosable因此需要关闭它。 Not naming the variable will not close it automatically.不命名变量不会自动关闭它。

Does the stream close when you use something like:当您使用以下内容时,流是否关闭:

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

It does not.它不是。 You should close it using try-with-resources, or a try-catch-finally block.您应该使用 try-with-resources 或 try-catch-finally 块关闭它。


Since JDK 7, the preferred way to close an AutoClosable is to use try-with-resources (like in your second snippet):从 JDK 7 开始,关闭 AutoClosable 的首选方法是使用 try-with-resources(就像在您的第二个代码段中一样):

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

Or you could call close() using a try-catch-finally block:或者您可以使用 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();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM