利用字节流和字节数组流是实现文件的复制

package ioxuexi;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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;
/**
* 利用字节流和字节数组流是实现文件的复制
* @author User
*
*/

public class lianxi17 {
public static void main(String[] args) throws IOException {
byte[] data=get("E:/test/2.txt");
set(data, "e:/test/45.txt");
}
//将目的字节数组放到目标区域
public static void set(byte[] src,String destString) throws IOException{
//创建目的文件源
File destFile=new File(destString);
//利用字节数组输入流录入字节数组
InputStream isInputStream=new BufferedInputStream(new ByteArrayInputStream(src));
//利用字节输出流输出文件
OutputStream bosOutputStream=new BufferedOutputStream(new FileOutputStream(destFile));
//进行操作
byte[] flush=new byte[1024];
int len=0;
while (-1!=(len=isInputStream.read(flush))) {
bosOutputStream.write(flush,0,len);
}
//强制刷出
bosOutputStream.flush();
//关闭文件流,释放资源
isInputStream.close();
bosOutputStream.close();

}
//通过字节流录入和字节数输出将源文件转换为字节数组
public static byte[] get(String pathname) throws IOException {
//创建文件源
File srcFile=new File(pathname);
byte[] dest=null;
//利用字节输入流将目的地址的文件进行录入
InputStream isInputStream=new BufferedInputStream(new FileInputStream(srcFile));
//创建字节数组输出流
ByteArrayOutputStream bosArrayOutputStream=new ByteArrayOutputStream();
//进行字节数组录入
byte[] flush=new byte[1024];
int len=0;
while (-1!=(len=isInputStream.read(flush))) {
bosArrayOutputStream.write(flush,0,len);
}
bosArrayOutputStream.flush();
//关闭文件流,释放资源
isInputStream.close();
bosArrayOutputStream.close();
//返回一个字节数组
return bosArrayOutputStream.toByteArray();

}
}

原文地址:https://www.cnblogs.com/zx931880423/p/6842962.html