6.10 封装输入输出流

封装输入输出流

说明

      将文件拷贝方法封装为一个方法,使之适应普遍的应用场合。

代码

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
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;

/**
 * 1、封装拷贝
 * 2、封装释放
 * @author dxt
 *
 */
public class FileUtils {
	public static void main(String[] args){
		//1. 测试对接输入输出流, 文件--->文件
		try {
			InputStream is = new FileInputStream("F:/myjava/IO_Study02/abc.txt");
			OutputStream os = new FileOutputStream("F:/myjava/IO_Study02/abc_copy.txt");
			copy(is, os);
		} catch (IOException e) {
			e.printStackTrace();
		}
		//2. 文件--->字节数组
		byte[] datas = null;
		try {
			InputStream is = new FileInputStream("F:/myjava/IO_Study02/bg.jpg");
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			copy(is, os);
			datas = os.toByteArray();
			System.out.println(datas.length);
		} catch (IOException e) {
			e.printStackTrace();
		}
		//3. 字节数组--->文件
		try {
			InputStream is = new ByteArrayInputStream(datas);
			OutputStream os = new FileOutputStream("F:/myjava/IO_Study02/bg_copy.jpg");
			copy(is, os);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 对接输入输出流
	 * @param fis
	 * @param fos
	 */
	public static void copy(InputStream fis, OutputStream fos){
		try {
			//3.1 分段读取操作
			byte[] flush = new byte[1024];
			int len = -1;
			while((len = fis.read(flush)) != -1){
				fos.write(flush, 0, len);	//3.2 写操作
			}
			fos.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e){
			e.printStackTrace();
		} finally{
			//4. 释放资源, 先打开的后关闭
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			try {
				fis.close();
			} catch (IOException e){
				e.printStackTrace();
			}
		}
	}
	/**
	 * IO流释放
	 * @param fis
	 * @param fos
	 */
	public static void close(InputStream fis, OutputStream fos){
		try {
			if(null != fos){
				fos.close();
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			if(null != fos){
				fis.close();
			}
		} catch (IOException e){
			e.printStackTrace();
		}
	}
	/**
	 * 重载
	 * @param io
	 */
	public static void close(Closeable... ios){	//...可变参数
		for(Closeable io : ios){
			try {
				if(null != io){
					io.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值