对于字节流byte[] bytes,写入文件,是一个通用方法,生成的文件只有扩展名不同,可以是任意属性文件【PDF,JPG,PNG,EXE,DLL……】。
附上代码:
public static boolean writeFile(byte[] bytes, String filePath) {
boolean flag = false;
if (StringUtils.isNotEmpty(filePath) && bytes.length > 0) {
mkdirs(filePath);
try (FileOutputStream fos = new FileOutputStream(filePath)) {
fos.write(bytes);
flag = true;
} catch (IOException e) {
log.error("写入文件时出现错误:" + e.getMessage());
}
}
return flag;
}
public static boolean mkdirs(String filepath) {
boolean retBool = true;
//TODO:判断文件及路径是否存在
if (StringUtils.isEmpty(filepath) || !filepath.contains("/")) {
return false;
}
String path = filepath.substring(0, filepath.lastIndexOf("/"));
File file = new File(path);
if (file.exists()) {
if (!file.isDirectory()) {
file.delete();
file.mkdirs();
}
} else {
file.mkdirs();
}
return retBool;
}
上面用到判定空的依赖:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.14.0</version>
</dependency>
对于文件路径的判定符,没有使用:File.separator,因为这个File.separator在Windows下是"\",在Linux下是"/",但是在Java语言里面路径符"/"是通用的,而"\"不通用,我们写代码需要注意。