try-catch常规的格式是try{……}catch(){……}finallly{……},如果优化成try(……){……}catch(){……}finallly{……},此时流就可以自动关闭,不需要手动去关闭。
File file = null;
OutputStream out = null;
try {
byte[] b = org.apache.commons.codec.binary.Base64.decodeBase64(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
//生成jpeg图片
out = new FileOutputStream(file);
out.write(b);
out.flush();
return file;
} catch (Exception e) {
log.error("FileUtil.base64ToJpg",e);
return file;
} finally {
if (out != null) {
try {
out.close();
} catch (Exception ex) {
log.error("FileUtil.base64ToJpg",ex);
}
}
}
JDK7 后 写成
try (OutputStream out = new FileOutputStream(file)){
byte[] b = org.apache.commons.codec.binary.Base64.decodeBase64(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
//生成jpeg图片
out.write(b);
out.flush();
return file;
} catch (Exception e) {
log.error("FileUtil.base64ToJpg",e);
}
return file;
详细解释看图片
