FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1)
bos.write(b, 0, n);
fis.close();
bos.close();
buffer = bos.toByteArray();
}catch (FileNotFoundException e){
e.printStackTrace();
catch (IOException e){
e.printStackTrace();
return buffer;
* byte 转file
public static File byte2File(byte
[]
buf, String filePath, String fileName){
BufferedOutputStream
bos
= null
FileOutputStream
fos
= null
File
file
= null
File
dir
= new File(filePath)
if (!dir.exists() && dir.isDirectory()){
dir.mkdirs()
file
= new File(filePath + File.separator + fileName)
fos
= new FileOutputStream(file)
bos
= new BufferedOutputStream(fos)
bos.write(buf)
}catch (Exception e){
e.printStackTrace()
finally{
if (bos != null){
bos.close()
}catch (IOException e){
e.printStackTrace()
if (fos != null){
fos.close()
}catch (IOException e){
e.printStackTrace()
return file
multipartFile转File
public static File multipartFile2File(MultipartFile multipartFile){
File file = null;
if (multipartFile != null){
try {
file=File.createTempFile("tmp", null);
multipartFile.transferTo(file);
System.gc();
file.deleteOnExit();
}catch (Exception e){
e.printStackTrace();
log.warn("multipartFile转File发生异常:"+e);
return file;
1、通常我们在文件的上传和下载的时候,一般参数我们用的都是MultipartFile对象,但是在我们存储或者保存到数据库时,却用的是byte字节数组,下面贴个简单的代码事例吧!
需要借助io流进行处理,流在传输的过程中,使用的是字节或者字符,具体如下
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import com.alibaba.fastjson.JSON;
public class FileUtil {
//将文件转换成Byte数组
public static byte[] getBytesByFile(String pathStr) {
File file = new File(pathStr)
try {
FileInputStream fis = new FileInputStream(file)
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000)
byte[] b = new byte[1000]
int n
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n)
fis.close()
byte[] data = bos.toByteArray()
bos.close()
return data
} catch (Exception e) {
e.printStackTrace()
return null
//将Byte数组转换成文件
public static void getFileByBytes(byte[] bytes, 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(bytes)
} 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()
public static void main(String[] args) {
// 获取图片字节数组
byte[] bytesByFile = getBytesByFile("E:\0.jpg");
System.out.println("bytesByFile:"+JSON.toJSONString(bytesByFile));
getFileByBytes(bytesByFile, "E:\\test1"+File.separator, "xxxx.jpg");
3、响应结果: