一种资源包装另一种资源时的Java try-with-resource

时间:2018-11-01 13:55:50

标签: java try-with-resources

让我们说我需要这个实例new BufferedReader(new InputStreamReader(new FileInputStream(path))),用try with resource编写此实例的最佳方法是什么。

1。我以前写的东西-因为只有第一个Closable需要关闭

try (FileInputStream fileInputStream = new FileInputStream(path)) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
    ...
}

2。最外部的Closable关闭其内部的Closable等。

try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path)))) {
    ...
}

3。为每个Closable使用单独的资源

try (
        FileInputStream fileInputSream = new FileInputStream(path);
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputSream);
        BufferedReader reader = new BufferedReader(fileInputSream)) {
    ...
}

谢谢

Ido Sorozon

1 个答案:

答案 0 :(得分:0)

我建议使用一种更具可读性的选项(提取方法):

{
    'classification': 'yarn-site',
    'Properties': {     'yarn.resourcemanager.scheduler.class':'org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairScheduler'
        }
}