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

java IO流复制图片

时间:2016-12-15 09:14:43      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:gbk   标记   runtime   byte   cep   otf   flush   new   需要   

一.使用字节流复制图片

 

 

//字节流方法
      public static void copyFile()throws IOException {
          
          //1.获取目标路径
          //(1)可以通过字符串
  //        String srcPath = "E://11.jpg";
  //        String destPath = "E://22.jpg";          
          //(2)通过文件类
         File srcPath = new File("E://11.jpg");
         File destPath = new File("E://22.jpg");         
         //2.创建通道,依次 打开输入流,输出流
         FileInputStream fis = new FileInputStream(srcPath);
         FileOutputStream fos = new FileOutputStream(destPath);
 
         byte[] bt = new byte[1024];
            //3.读取和写入信息(边读取边写入)
         while (fis.read(bt) != -1) {//读取
             fos.write(bt);//写入
         }
 
         //4.依次 关闭流(先开后关,后开先关)
         fos.close();
         fis.close();
     }

 

 

二.使用字符流复制图片

  //字符流方法,写入的数据会有丢失
      public static void copyFileChar()throws IOException {
          
          //获取目标路径
          File srcPath = new File("E://11.jpg");
      File destPath = new File("E://22.jpg"); //创建通道,依次 打开输入流,输出流 FileReader frd = new FileReader(srcPath); FileWriter fwt = new FileWriter(destPath); char[] ch = new char[1024]; int length = 0; // 读取和写入信息(边读取边写入) while ((length = frd.read(ch)) != -1) {//读取 fwt.write(ch,0,length);//写入 fwt.flush(); }   // 依次 关闭流(先开后关,后开先关) frd.close(); fwt.close(); }

 

三.复制图片过程中的异常处理

 

//以复制图片为例,实现try{ }cater{ }finally{ } 的使用
         public static void test(){
              //1.获取目标路径
             File srcPath = new File("E://11.jpg");
      File destPath = new File("E://11.jpg");
//2.创建通道,先赋空值 FileInputStream fis = null; FileOutputStream fos = null; //3.创建通道时需要抛出异常 try { fis = new FileInputStream(srcPath); fos = new FileOutputStream(destPath); byte[] bt = new byte[1024]; //4.读取和写入数据时需要抛出异常 try { while(fis.read(bt) != -1){ fos.write(bt); } } catch (Exception e) { System.out.println("储存盘异常,请修理"); throw new RuntimeException(e); } } catch (FileNotFoundException e) { System.out.println("资源文件不存在"); throw new RuntimeException(e); }finally{
//5.无论有无异常,需要关闭资源(分别抛出异常) try { fos.close(); } catch (Exception e) { System.out.println("资源文件或目标文件关闭失败!"); throw new RuntimeException(e); }
try { fis.close(); } catch (IOException e) { System.out.println("资源文件或目标文件关闭失败!"); throw new RuntimeException(e); } } }

 

字符流  =  字节流 + 解码 --->找对应的码表  GBK

  字符流解码 拿到系统默认的编码方式来解码

将图片中的二进制数据和GBK码表中的值进行对比, 对比的时候会出现二进制文件在码表中找不对应的值,他会将二进制数据标记为未知字符,当我在写入数据的是后会将未知的字符丢掉。所以会造成图片拷贝不成功(丢失数据)

疑问:何时使用字节流?何时使用字符流?

  使用字节流的场景:读写的数据不需要转为我能够看得懂的字符。比如:图片,视频,音频...

  使用字符流的场景 :如果读写的是字符数据。

java IO流复制图片

标签:gbk   标记   runtime   byte   cep   otf   flush   new   需要   

原文地址:http://www.cnblogs.com/houjiie/p/6181839.html

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