SonarLint Try-with-resources should be used
在文件流中,我们在使用完这些流通道都需要将其关闭,并在该过程中捕获异常。通常我们的代码写法是下面这样
public static File byteToFile(byte[] buf, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists()) {
dir.mkdirs();
}
file = new File(filePath + "/" + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(buf);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return file;
}
public static File byteToFile(byte[] buf, String filePath, String fileName) {
File file = null;
try (FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos)) {
File dir = new File(filePath);
if (!dir.exists()) {
dir.mkdirs();
}
file = new File(filePath + "/" + fileName);
bos.write(buf);
} catch (Exception e) {
log.error("{}", e);
}
return file;
}
代码更加简洁明了。