版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Caiaixiong/article/details/85251115
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. 字节数组写出文件
*/
public class IOUtils {
public static void main(String[] args) {
byte[] datas = fileToByteArray("p.png");
System.out.println(datas.length);
byteArrayToFile(datas,"p-byte.png");
}
/**
* 1. 图片读取到字节数组
* 1)图片到程序 FileInputStream
* 2) 程序到字节数组 ByteArrayOutputStream
* @return
*/
public static byte[] fileToByteArray(String filePath){
File src = new File(filePath);
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
is = new FileInputStream(src);
baos = new ByteArrayOutputStream();
byte[] flush = new byte[1024*10];
int len = -1;
while((len = is.read(flush))!=-1){
baos.write(flush, 0, len);
}
baos.flush();
return baos.toByteArray();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(is!=null){
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
/**
* 2. 字节数组写出到图片
* 1) 字节数组到程序 ByteArrayInputStream
* 2) 程序到文件 FileOutputStream
*/
public static void byteArrayToFile(byte[] src,String filePath){
File dest = new File(filePath);
InputStream is = null;
OutputStream os = null;
try {
is = new ByteArrayInputStream(src);
os = new FileOutputStream(dest);
byte[] flush = new byte[1024];
int len = -1;
while((len=is.read(flush))!=-1){
os.write(flush,0,len);
}
os.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(os!=null){
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}