Java⼆进制数据转成⽂件
SqlServer数据库中,存储⽂件的字段的类型是image,对应的Java类型是byte[],下⾯的函数将演⽰如何把读取出来数据放⼊指定⽬录。当然,⾸先需要从数据库读出,然后调⽤该⽅法。
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileUtils {
private static Logger logger = Logger(FileUtils.class);
/**
* @Title: byteToFile
* @Description: 把⼆进制数据转成指定后缀名的⽂件,例如PDF,PNG等
* @param contents ⼆进制数据
* @param filePath ⽂件存放⽬录,包括⽂件名及其后缀,如D:\file\bike.jpg
* @Author: Wiener
* @Time: 2018-08-26 08:43:36
*/
public static void byteToFile(byte[] contents, String filePath) {
BufferedInputStream bis = null;
FileOutputStream fos = null;
java连接sqlserver数据库
BufferedOutputStream output = null;
try {
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(contents);
bis = new BufferedInputStream(byteInputStream);
File file = new File(filePath);
// 获取⽂件的⽗路径字符串
File path = ParentFile();
if (!ists()) {
logger.info("⽂件夹不存在,创建。path={}", path);
boolean isCreated = path.mkdirs();
if (!isCreated) {
<("创建⽂件夹失败,path={}", path);
}
}
fos = new FileOutputStream(file);
// 实例化OutputString 对象
output = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int length = ad(buffer);
while (length != -1) {
output.write(buffer, 0, length);
length = ad(buffer);
}
output.flush();
} catch (Exception e) {
<("输出⽂件流时抛异常,filePath={}", filePath, e);
} finally {
try {
bis.close();
fos.close();
output.close();
} catch (IOException e0) {
<("⽂件处理失败,filePath={}", filePath, e0);
}
}
}
}