IO、创建myread方法、拷贝图片/mp3

P243集

package CoreJavaPractice;

import java.io.*;
public class Practice_2 {
        public static void main(String[] args)  {
            
            /*
             复制一个图片
             思路:
             1、用字节读取流对象和图片关联
             2、用字节写入流对象创建一个图片文件,用于存储所获取到的数据。
             3、通过循环读写、完成数据的存储。
             4、关闭资源。
             */
            FileOutputStream fos = null;
            FileInputStream fis = null;
            try
            {
                fos = new FileOutputStream("张小龙.jpg");
                fis = new FileInputStream("ZhangXiaolong.jpg");
                
                byte[] buf = new byte[1024];
                int len = 0;
                while((len=fis.read(buf))!=-1)            //往容器里面装。 装到buf里面
                {
                    fos.write(buf,0,len);                  //要写有效数据,所以就是从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("写入关闭失败");
                }
            }
            
        
}
}

 

posted @ 2019-09-11 11:01  蚂蚁雅黑1010  阅读(184)  评论(0编辑  收藏  举报