字节流之复制图片的4种方式

package cn.itcast_02;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 * 复制图片
 * 
 * 分析:
 *     复制数据,如果我们用记事本打开并能够读懂,就用字符流,否则用字节流
 *     通过该原理,我们知道应该采用字节流
 *     而字节流有四种方式,所以我们做这道题目是有四种,推荐掌握第四种
 * 		1.高效流复制一次一个字节
 * 		2.高效流复制一次一个字节数组
 * 		3.基本字节流一次读取一个字符数组
 * 		4.基本字节流一次读取一个字符
 * 
 * 数据源:E:\\流浪地球.jpg --- FileInputStream ---BufferedInPutStream
 * 
 * 目的地:C:\\流浪地球.jpg  --- FileOutputStream --- BuffereOutputStream
 */
public class 复制图片的4种方式 {

	public static void main(String[] args) throws IOException {
		//使用字符串作为路径
	    //String srcString = "E:\\流浪地球.jpg";
		//String desString = "C:\\流浪地球.jpg ";
		//使用File对象作为路径
		File srcFile = new File("E:\\流浪地球.jpg");
		File desFile = new File("E:\\流浪地球.jpg");
         
		methon1(srcFile ,desFile);
		methon2(srcFile ,desFile);
		methon3(srcFile ,desFile);
		methon4(srcFile ,desFile);

	}

	//基本字节流一次读取一个字符
	private static void methon4(File srcFile, File desFile) throws IOException {
		// 封装数据源
		FileInputStream fi = new FileInputStream(srcFile);
		//封装目的地
		FileOutputStream fw = new FileOutputStream(desFile);
		
		//复制
		int by = 0;
		while((by = fi.read()) != -1) {
			fw.write(by);
		}
		
		//释放资源
		fi.close();
		fw.close();
	}

	//基本字节流一次读取一个字符数组
	private static void methon3(File srcFile, File desFile) throws IOException {
		// 封装数据源
		FileInputStream fi = new FileInputStream(srcFile);
		//封装目的地
		FileOutputStream fw = new FileOutputStream(desFile);
				
		//复制
		byte[] by = new  byte[1024];
		int len = 0;
		while((len = fi.read(by)) != -1) {
			fw.write(by , 0 , len);
		}
				
		//释放资源
		fi.close();
		fw.close();
	}


	//高效流复制一次一个字节数组
	private static void methon2(File srcFile, File desFile) throws IOException {
		// 封装数据源
		BufferedInputStream bi = new BufferedInputStream(new FileInputStream(srcFile));
		//封装目的地
		BufferedOutputStream bw =new BufferedOutputStream( new FileOutputStream(desFile));
						
		//复制
		byte[] by = new  byte[1024];
		int len = 0;
		while((len = bi.read(by)) != -1) {
			bw.write(by , 0 , len);
		}
						
		//释放资源
		bi.close();
		bw.close();
	}


	//高效流复制一次一个字节
	private static void methon1(File srcFile, File desFile) throws IOException {
		// 封装数据源
		BufferedInputStream bi = new BufferedInputStream(new FileInputStream(srcFile));
		//封装目的地
		BufferedOutputStream bw =new BufferedOutputStream( new FileOutputStream(desFile));
		
		//复制
		int by = 0;
		while((by = bi.read()) != -1) {
					bw.write(by);
		}
				
		//释放资源
		bi.close();
		bw.close();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Unknown To Known

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值