以下代码是否有效?
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();
}
}