Java IO,这些资源是否自动关闭?

时间:2018-03-27 19:24:47

标签: java file-io io stream

在这段代码中,我读了一个文本文件,当BufferedReader被“try-resource”块关闭,所以InputStreamReader会这样做,那么我可以保证所有的资源都是这样关闭的吗?

try(final BufferedReader br = new BufferedReader(new InputStreamReader(new 
    FileInputStream(file), charset))) {
        String line = null;

        while((line = br.readLine()) != null) {
            builder.append(line);

        }

    }

在另一个例子中,我写了一个文本文件,正如写的那样,到底是关闭了所有资源?是否必须调用flush()?

try(final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new 
    FileOutputStream(file), charset))) {
        bw.write(text);
        bw.flush();

    }

1 个答案:

答案 0 :(得分:1)

是的,最外层的流调用其内部流'.tagsHolder { display: flex; flex-direction: row; margin-bottom: 10px; flex-wrap: wrap; .labelItem { display: flex; margin-right: 10px; align-items: center; margin-top: 2px; .labelContent, .labelAditional { font-weight: 600; padding: 5px 8px; height: 100%; display: flex; justify-content: center; align-items: center; } .labelContent { color: #fff; //background-color: #666; background-color: $gray-300; border-bottom-left-radius: 5px; border-top-left-radius: 5px; font-size: 0.7rem; } .labelAditional { color: #444; background-color: lighten(map-get($theme-colors, "success"), 10%); font-size: 0.6rem; } .labelClose { display: flex; justify-content: center; align-items: center; text-transform: uppercase; color: #fff; //background-color: #444; background-color: $gray-400; padding: 2px 6px; border-bottom-right-radius: 5px; border-top-right-radius: 5px; cursor: pointer; font-weight: 700; font-size: 0.7rem; height: 100%; position: relative; box-sizing: border-box; transition: all 0.25s ease-in-out; &:hover { //background-color: #555; background-color: $gray-500; } } } } 方法,因此您只需要调用最外层的流。

您无需致电close(),必要时和关闭之前,流将会刷新。删除它,代码看起来很完美。