java 复制图片练习

本文展示了如何使用Java的字节流复制图片。主要通过FileInputStream和FileOutputStream进行操作,分别演示了不使用缓冲区和使用缓冲区的两种方式。
摘要由CSDN通过智能技术生成
/*
复制图片。其实复制媒体文件用到的基本上是字节流文件。复制音乐与复制图片类似。
图片是媒体文件,所以要使用InputStream和OutputStream来进行复制操作。
*/
import java.io.*;
class CopyPicTest 
{
	public static void main(String[] args) 
	{
		long start=System.currentTimeMillis();
		copyPic();
		long mid=System.currentTimeMillis();
		copyPicArr();
		long end=System.currentTimeMillis();
		System.out.println("1:"+(mid-start)+"毫秒");
		System.out.println("2:"+(end-mid)+"毫秒");
	}


/*
不使用数组作为缓冲区
*/
	public static void copyPic()
	{
		FileInputStream fis=null;
		FileOutputStream fos=null;
		FileWriter fw=null;
		try
		{
			fis=new FileInputStream("D:\\图片\\20.jpg");
			fos=new FileOutputStream("D:\\图片\\21.jpg");
			fw=new FileWriter("D:\\图片\\pic.txt");

			int by;
			while((by=fis.read())!=-1)
			{
				fos.write((char)by);
				fw.write(by);
			}
		}
		catch (IOException e)
		{
			throw new RuntimeException("复制失败");
		}
		finally
		{
			try
			{
				if(fis!=null)
					fis.close();
			}
			catch (IOException e)
			{
				throw new RuntimeException("读取流对象关闭失败");
			}

			try
			{
				if(fos!=null)
					fos.close();
			}
			catch (IOException e)
			{
				throw new RuntimeException("写入流对象关闭失败");
			}
		}
	}
/**/
	public static void copyPicArr()
	{
		FileInputStream fis=null;
		FileOutputStream fos=null;
		try
		{
			fis=new FileInputStream("D:\\图片\\20.jpg");
			fos=new FileOutputStream("D:\\图片\\22.jpg");

			int len;
			byte[] b=new byte[1024];
			while((len=fis.read(b))!=-1)
			{
				fos.write(b,0,len);
			}
		}
		catch (IOException e)
		{
			throw new RuntimeException("复制失败");
		}
		finally
		{
			try
			{
				if(fis!=null)
					fis.close();
			}
			catch (IOException e)
			{
				throw new RuntimeException("读取流对象关闭失败");
			}

			try
			{
				if(fos!=null)
					fos.close();
			}
			catch (IOException e)
			{
				throw new RuntimeException("写入流对象关闭失败");
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值