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

package testdemo;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
	    /**
	    * 利用字节流和字节数组流是实现文件的复制
	    * @author User
	    *
	    */

public class testCopy {
	
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();
	
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值