黑马程序员技术交流社区

标题: IO流中复制图片的代码整理 [打印本页]

作者: 淡淡柠檬茶    时间: 2014-6-6 12:49
标题: IO流中复制图片的代码整理
//复制一个图片
import java.io.*;
class  CopyPic
{
        public static void main(String[] args) throws IOException
        {
                /*方法1
                FileOutputStream ou = new FileOutputStream("C:\\.2.jpg");
                FileInputStream in = new FileInputStream("C:\\1.jpg");
                int num = 0;
                while ((num = in.read())!=-1)
                {
                        ou.write(num);
                }
                ou.close();
                in.close();
                */


                //方法2
                FileOutputStream ou = new FileOutputStream("C:\\.2.jpg");
                FileInputStream in = new FileInputStream("C:\\1.jpg");
                byte[] bvf = new byte[in.available()];
                in.read(bvf);
                ou.write(bvf);
               
                ou.close();
                in.close();


                /*方法3
                FileOutputStream ou = null;
                FileInputStream in = null;
                try
                {
                        ou = new FileOutputStream("c:\\.2.jpg");
                        in = new FileInputStream("c:\\1.jpg");
                        
                        //byte[] bvf = new byte[1024];
                        //int len = 0;
                        //while((len = in.read(bvf))!=-1)
                        //{
                        //        ou.write(bvf,0,len);
                        //}
                        
                        byte[] bvf = new byte[in.available()];
                        in.read(bvf);
                        ou.write(bvf);
               
                }
                catch (Exception e)
                {
                        throw new RuntimeException("复制失败");
                }
                finally
                {
                        if(in!=null)
                        try
                        {
                                in.close();
                        }
                        catch (Exception e)
                        {
                                throw new RuntimeException("读取失败");
                        }
                        if(ou!=null)
                        try
                        {
                                ou.close();
                        }
                        catch (Exception e)
                        {
                                throw new RuntimeException("写入失败");
                        }
                }
                */
        }
}

作者: 淡淡柠檬茶    时间: 2014-6-6 12:52
对了,方法2中可以不采用available()方法,这样的话就有4种了
作者: superob123    时间: 2014-6-6 14:34
好的原来可以这样!!




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2