import java.io.*;
/**
* 对接流
*/
public class DockingStream {
//文件通过文件字节输入流转换为字节数组后通过字节数组输出流输出到字节数组中
public byte[] fileToByteArray(String FilePath) throws IOException {
byte[] flush = new byte[1024*10];//缓冲容器
int len = -1;//辅助变量,显示缓冲容器当前的长度
File url = new File(FilePath);//确定源
InputStream Is = null;
ByteArrayOutputStream Baos;
try{
//确定流
Is = new FileInputStream(url);
Baos = new ByteArrayOutputStream();
//操作
while((len = Is.read(flush)) != -1){
Baos.write(flush,0,len);
}
Baos.flush();
return Baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}finally {
//释放资源
assert Is != null;
Is.close();
}
return null;
}
//字节数组输入流接收到字节数组后通过文件字节输出流将字节数组输出为文件
public void bytearrayToFile(byte[] src, String FilePath) throws IOException {
byte[] flush = new byte[1024*10];//缓冲容器
int len = -1;//辅助变量,显示缓冲容器当前的长度
File url = new File(FilePath);//确定源
OutputStream Os = null;
ByteArrayInputStream Bais;
//确定流
try {
Os = new FileOutputStream(url);
Bais = new ByteArrayInputStream(src);
while((len = Bais.read(flush)) != -1){
Os.write(flush,0,len);
}
Os.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
assert Os != null;
Os.close();
}
}
}
主类
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
DockingStream ds = new DockingStream();
byte[] datas = ds.fileToByteArray("C:\\Users\\DaluxC\\Desktop\\新建文件夹δ\\sunflower.png");
ds.bytearrayToFile(datas, "F:\\Java\\IO Study 04\\src\\sunflower.png");
}
}