package io02;
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
/
public class TestIO {
public static void main(String[] args) {
byte[] dates = fileToByteArray(“1.jpg”);
System.out.println(dates.length);
byteArrayToFile(dates, “text.jpg”);
}
/*
* 图片读取到字节数组
* 1.图片到程序 FileInputStreeam
* 2.程序到字节数组 ByteArrayOutputStream
* @param path
*/
public static byte[] fileToByteArray(String path) {
//1.创建源与目的地
File src = new File(path);
byte[] dest = null;
//2.选择流
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
is = new FileInputStream(src);
baos = new ByteArrayOutputStream();
//3.操作(分段读取)
byte[] temp = new byte[1024]; //缓冲容器
int len = -1; //接收长度
while((len = is.read(temp)) != -1) {
baos.write(temp,0,len); //写出到字节数组
}
baos.flush();
return baos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//4.释放资源
try {
if(null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 字节数组写出到图片
* 1.字节数组到程序 ByteArrayInputStream
* 2.程序写出到文件 FileOutputStream
* @param src
* @param filePath
*/
public static void byteArrayToFile(byte[] src,String filePath) {
//1.创建源
File f = new File(filePath);
//2.选择流
InputStream is = null;
OutputStream os = null;
try {
is = new ByteArrayInputStream(src);
os = new FileOutputStream(f);
//3.操作(分段读取)
byte[] temp = new byte[1024];//缓冲容器
int len = -1; //接收长度
while((len = is.read(temp)) != -1) {
os.write(temp,0,len);
}
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(null != os) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}