日志文章

2019-12-23 aflfte2011

利用IO字节数组流实现文件拷贝

package com.aflfte.IO;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 1、图片读取到字节数组
 * 2、字节数组输出到文件
 * @author jinhao
 *
 */
public class Test11 {
public static void main(String[] args) {
byte[] datas=fileToByteArray("F:\\jinhao\\Desktop\\12.png");
System.out.println(datas.length);
byteArrayToFile(datas, "2.png");

}
//图片到字节数组
public static byte[] fileToByteArray(String path) {
File f=new File(path);
//byte[] dest=null;
InputStream is=null;
ByteArrayOutputStream bo=null;
try {
is=new FileInputStream(f);
bo=new ByteArrayOutputStream();
byte[] flush=new byte[1024*10];
int len=-1;
while((len=is.read(flush))!=-1) {
bo.write(flush,0,len);//写出到字节数组中
}
bo.flush();
return bo.toByteArray();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally {
if(is!=null) {
try {
is.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
return null;

}

//字节数组到图片
public static void byteArrayToFile(byte[] src,String filepath) {
InputStream is=null;
File dest=new File(filepath);
OutputStream os=null;
try {
os=new FileOutputStream(dest);

is=new ByteArrayInputStream(src);
byte[] flush=new byte[5];
int len=-1;
try {
while((len=is.read(flush))!=-1) {
os.write(flush,0,len);
}
os.flush();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}finally {
if(os!=null) {
try {
os.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}
}


« 拷贝的封装与资源释放方法 | IO字节数组输入流与输出流的使用»