上个月学习了IO,感觉不扎实,写个笔记IO的文件与字节数组交互实现上传下载,多思考思考
public class IOUtils{
//文件转成字节数组
public static byte[] fileToByteArray(String filePath){
//创建源
File src = new File(filePath);
byte[] dest = null;
//选择流
InputStream is = null;
ByteArrayOutputStream baos = null;
try{
is = new FileInputStream(src);//文件输入流
baos = new ByteArrayOutputStream();//字节输出流
//操作 分段读取
byte[] bf = new byte[1024*10];
int len = -1;
whlie((len = is.read(bf)) != -1){
baos.write(bf,0,len);
}
baos.flush();//刷新
return baos.toByteArray();//返回字节数组
}catch(Exception e){
e.printStackTrace();
}
return null;
}
//字节数组写出到文件
public static void byteArrayToFile(bytr[] src,String filePath){
//创建源
File dest = new File(filePath);
//选择流
InputStream is = null;
OutputStream os = null;
try{
is = new ByteArrayInputStream(src);//字节输入流
os= new FileOutputStream(dest);//文件输出流
//操作 分段读取
byte[] fr = new byte[5];
int len = -1;
while((len = is.read(fr)) != -1){
os.write(bf,0,len);
}
os.flush();
}catch(Exception){
e.printStackTrace();
}finally{
try {
if (null != os) {
os.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
各位大佬们有建议我及时改正,谢谢提点!