返回资源时尝试使用资源

时间:2018-02-07 00:34:53

标签: java stream try-catch outputstream

以下代码是否有效?

public ConvertibleOutputStream toOutputStream(Type type, Details 
details) 
  {
    try(ConvertibleOutputStream outputStream = new ConvertibleOutputStream();) {
        details.toJson(outputStream);
        return outputStream;
    } catch (IOException e) {
        throw new CustomException();
    }
} 

流在try-with-resources块中初始化,并在try块中返回。流回来之前会关闭吗?我应该用以下格式编写代码:

public ConvertibleOutputStream toOutputStream(Type type, Details 
details) 
  {
   ConvertibleOutputStream outputStream = null;
    try{
        outputStream = new ConvertibleOutputStream();
        details.toJson(outputStream);
        return outputStream;
    } catch (IOException e) {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException ex) {
                throw new CustomException();
            }
        }
        throw new CustomException();
    }
}

0 个答案:

没有答案
相关问题