文件二进制互转

/**
* 将文件转换成byte数组
* @param tradeFile
* @return
*/
public static byte[] File2byte(File tradeFile){
byte[] buffer = null;
try
{
FileInputStream fis = new FileInputStream(tradeFile);
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数组转换成文件 (输出到指定目录)
* filePath 文件输出路径
*/
public static void byte2File(byte[] byte1,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+fileName);
fos=new FileOutputStream(file);
bos=new BufferedOutputStream(fos);
bos.write(byte1);
}
catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
finally{
try{
if(bos != null){
bos.close();
}
if(fos != null){
fos.close();
}
}
catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}

猜你喜欢

转载自www.cnblogs.com/MrYangSX/p/11655056.html