您的位置:首页 > 编程语言 > Java开发

java 复制图片练习

2016-05-11 10:49 387 查看
/*
复制图片。其实复制媒体文件用到的基本上是字节流文件。复制音乐与复制图片类似。
图片是媒体文件,所以要使用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 复制图片