IO流_复制图片的4种方式案例

101 篇文章 0 订阅
85 篇文章 0 订阅
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;

/*
 * 复制图片
 * 
 * 分析:
 * 		复制数据,如果我们能用记事本打开并能读懂,就用字符流,否则用字节流。
 * 		通过该原理,我们知道我们应该采用字节流
 * 		而字节流有4种方式,所以这个题目我们有4种方式。推荐撑握第4种。
 * 
 * 数据源
 * 		c:\\a.jpg	--	FileInputStream	--	BufferedInputStream
 * 目的地
 * 		d:\\b.jpg	--	FileOutputStream	--	BufferedOutputStream
 */
public class CopyImageDemo {
	public static void main(String[] args) throws IOException {
		// 使用字符串路径
		// String srcFile = "c:\\a.jpg";
		// String destFile = "d:\\b.jpg";
		// 使用File作为参数
		File srcFile = new File("c:\\a.jpg");
		File destFile = new File("d:\\b.jpg");

		// method1(srcFile, destFile);
		// method2(srcFile, destFile);
		// method3(srcFile, destFile);
		method4(srcFile, destFile);
	}

	// 方式4:高效字节流一次读写一个字节数组
	public static void method4(File srcFile, File destFile)
			throws IOException {
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
				srcFile));
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(destFile));

		byte[] bys = new byte[1024];
		int len = 0;
		while ((len = bis.read(bys)) != -1) {
			bos.write(bys, 0, len);
			bos.flush();
		}

		bos.close();
		bis.close();
	}

	// 方式3:高效字节流一次读写一个字节
	public static void method3(File srcFile, File destFile)
			throws IOException {
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
				srcFile));
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(destFile));

		int len = 0;
		while ((len = bis.read()) != -1) {
			bos.write(len);
		}

		bos.close();
		bis.close();
	}

	// 方式2:基本字节流一次读写一个字节数组
	public static void method2(File srcFile, File destFile)
			throws IOException {
		FileInputStream fis = new FileInputStream(srcFile);
		FileOutputStream fos = new FileOutputStream(destFile);

		byte[] bys = new byte[1024];
		int len = 0;
		while ((len = fis.read(bys)) != -1) {
			fos.write(bys, 0, len);
			fos.flush();
		}

		fos.close();
		fis.close();
	}

	// 方式1:基本字节流一次读写一个字节
	public static void method1(File srcFile, File destFile)
			throws IOException {
		FileInputStream fis = new FileInputStream(srcFile);
		FileOutputStream fos = new FileOutputStream(destFile);

		int len = 0;
		while ((len = fis.read()) != -1) {
			fos.write(len);
		}

		fos.close();
		fis.close();
	}
}

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值