码迷,mamicode.com
首页 > 编程语言 > 详细

java 复制图片练习

时间:2016-05-12 12:10:16      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

/*
复制图片。其实复制媒体文件用到的基本上是字节流文件。复制音乐与复制图片类似。
图片是媒体文件,所以要使用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("写入流对象关闭失败");
			}
		}
	}
}

java 复制图片练习

标签:

原文地址:http://blog.csdn.net/iemdm1110/article/details/51372530

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!