業(yè)務場景:
在異步線程中,主線程提交了一個文件,子線程接收文件后出現(xiàn)文件大小變?yōu)椤?”的情況。
原因:文件從主線程到子線程連接斷開衔憨,導致文件上傳數(shù)據(jù)丟失
處理方式:在主線程中將文件轉為byte數(shù)組,在子線程接收該數(shù)組后再將數(shù)組轉為文件袄膏。
File與byte數(shù)組的相互轉換
public class FileUtil {
/**
* file轉byte
*/
public static byte[] file2byte(File file){
byte[] buffer = null;
try{
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;
try{
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){
try{
bos.close();
}catch (IOException e){
e.printStackTrace();
}
}
if (fos != null){
try{
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發(fā)生異常:"+e);
}
}
return file;
}
}