黑马程序员技术交流社区

标题: 字节流问题,请大虾帮忙 [打印本页]

作者: 任我行    时间: 2014-12-16 17:23
标题: 字节流问题,请大虾帮忙
代码是用于复制一张图片,运行成功,但复制出来的图片字节为0,不能打开。。
  1. public class CopyPic
  2. {
  3.         public static void main(String[] args)
  4.         {
  5.                 FileOutputStream fos = null;
  6.                 FileInputStream fis = null;
  7.                 try
  8.                 {
  9.                         fos = new FileOutputStream("C:\\2.jpg");
  10.                         fis = new FileInputStream("C:\\1.jpg");
  11.                        
  12.                         byte[] buf = new byte[1024];
  13.                        
  14.                         int lenght = 0;
  15.                        
  16.                         while (-1 !=(fis.read(buf)))
  17.                         {
  18.                                 fos.write(buf,0,lenght);
  19.                         }
  20.                 } catch (IOException e)
  21.                 {
  22.                         throw new RuntimeException("复制文件失败");
  23.                 }
  24.                 finally
  25.                 {
  26.                         try
  27.                         {
  28.                                 if (fis != null)
  29.                                 {
  30.                                         fis.close();
  31.                                 }
  32.                         } catch (IOException e2)
  33.                         {
  34.                                 throw new RuntimeException("读取文件失败");
  35.                         }
  36.                         try
  37.                         {
  38.                                 if (fos != null)
  39.                                 {
  40.                                         fos.close();
  41.                                 }
  42.                         } catch (IOException e2)
  43.                         {
  44.                                 throw new RuntimeException("写入文件失败");
  45.                         }
  46.                        
  47.                 }
  48.                
  49.         }
  50. }
复制代码

作者: huoxy    时间: 2014-12-16 17:28
lenght一直是0,所以复制失败!应该是while(-1!=(lenght = fis.read(buf)))! 另:长度应该是length单词(强迫症,伤不起)。
作者: 王世虎    时间: 2014-12-16 18:40
楼上哥们正解,我是这个length怎么看着难受 哈哈
作者: 任我行    时间: 2014-12-17 09:33
哈哈哈  多谢指点:handshake




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