思路:
fileToByteArray:把文件转换成字节数组
先用FileInputStream 的read 方法把文件字节流存到flush字节数组
在用ByteArrayOutputStream 的write方法从flush里读出来存到OutputStream的缓存数组里
最后把byteArrayOutputStream.toByteArray() return出去
byteArrayToFile:把字节数组转换成文件
先用ByteArrayInputStream 的read方法把OutputStream的缓存数组里的数据读取出来保存到flush数组里
在用FileOutputStream从flush数组里读取数据写入到目标文件
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class IO_Test06 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
byteArrayToFile(fileToByteArray("13.png"), "16.png");
}
public static byte[] fileToByteArray(String srcPath) throws IOException {
File srcFile = new File(srcPath);// 创建源
InputStream iStream = new FileInputStream(srcFile);
byte[] flush = new byte[1024];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int temp = -1;
while ((temp = iStream.read(flush)) != -1) {//从srcFile里读并保存到flush里
byteArrayOutputStream.write(flush);//从flush里读出来写到outputstream的缓存数组里,并不是存到flush数组里
}
iStream.close();
return byteArrayOutputStream.toByteArray();
}
public static void byteArrayToFile(byte[] src, String filePath) throws IOException {
File desFile = new File(filePath);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(src);
OutputStream oStream = new FileOutputStream(desFile);
int len = -1;
byte[] flush = new byte[1024];
while ((len = byteArrayInputStream.read(flush)) != -1) {
oStream.write(flush, 0, len);
}
oStream.flush();
oStream.close();
}
}