通过文件流和字节数组流实现文件的拷贝

本文详细介绍了如何利用Java的文件流和字节数组流进行文件复制操作,包括步骤解析和代码示例,旨在提供一种高效、可靠的文件拷贝解决方案。
摘要由CSDN通过智能技术生成
package com.gk;

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 GuoKe
 *
 */
public class IOTest9 {
	public static void main(String[] args) {
		byte[] bt = fileToByteArray("C:/Users/GK/Desktop/test.jpg");
		System.out.println(bt.length);
		byteArrayToFile(bt, "C:/Users/GK/Desktop/test00.jpg");
	}
	
	public static byte[] fileToByteArray(String filePath) {
		
		//1.创建源
		File src = new File(filePath);
		InputStream is = null;
		ByteArrayOutputStream bs = null;

		bs = new ByteArrayOutputStream();
		try {
			//2.选择流
			is = new FileInputStream(src);
			//3.操作
			byte[] flush = new byte[1024];//缓冲容器
			int len = -1;//接收长度
			while((len=is.read(flush)) != -1) {
				bs.write(flush,0,len);
			}
			bs.flush();
			return bs.toByteArray();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(is!=null) {
					//4.释放资源
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return null;
		
	}
	
	public static void byteArrayToFile(byte[] src, String filePath) {
		
		File dest = new File(filePath);
		OutputStream os = null;
		InputStream is = null;
		try {
			//2.选择流
			os = new FileOutputStream(dest);
			is = new ByteArrayInputStream(src);
			//3.操作
			byte[] flush = new byte[1024];//缓冲容器
			int len = -1;//接收长度
			while((len=is.read(flush)) != -1) {
				os.write(flush,0,len);	
			}
			os.flush();
		}  catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if (os != null) {//alt+shift+z
					os.close();
				} 
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值