黑马程序员技术交流社区

标题: 拷贝失败 [打印本页]

作者: 张云刚    时间: 2014-5-24 22:05
标题: 拷贝失败
public static void main(String[] args) {
                // TODO Auto-generated method stub
                FileOutputStream fos = null;
                FileInputStream fis = null;
                try {
                        fos = new FileOutputStream("E:\\3.jsp");
                        fis = new FileInputStream("D:\\1.jsp");
                        byte[] buf = new byte[10242222];
                        int len = 0;
                        while ((len = fis.read(buf))!= -1) {
                                fos.write(buf, 0, len);
                        }
                } catch (IOException e) {
                        // TODO: handle exception
                        //throw new RuntimeException("复制文件失败");




为什么拷贝txt文件,就可以成功拷贝,拷贝图片就失败呢,拷贝过去的图片无法打开,并且是0字节的
作者: 月光海    时间: 2014-5-24 22:32
我能说在我这成功了吗?
作者: 波涛    时间: 2014-5-24 22:45
因为你没有关闭流啊,记得流使用完了要关闭close()的,要释放资源。否则复制的东西仍然只是在内存中驻留而已。

  1. import java.io.*;

  2. public class Demo {
  3. public static void main(String[] args) {
  4.                 FileOutputStream fos = null;
  5.                 FileInputStream fis = null;
  6.                 try {
  7.                         fos = new FileOutputStream("E:\\3.jpg");
  8.                         fis = new FileInputStream("D:\\b.jpg");
  9.                         byte[] buf = new byte[10242222];
  10.                         int len = 0;
  11.                         while ((len = fis.read(buf))!= -1) {
  12.                                 fos.write(buf, 0, len);
  13.                         }
  14.                 } catch (IOException e) {
  15.                         // TODO: handle exception
  16.                         //throw new RuntimeException("复制文件失败");

  17.         }
  18.                 finally{
  19.                         
  20.                         try{
  21.                                 if (fos != null)
  22.                                         fos.close();
  23.                         }catch(IOException e){System.out.println(e.toString());}
  24.                           try{
  25.                                 if (fis != null)
  26.                                         fis.close();
  27.                         }catch(IOException e){System.out.println(e.toString());}
  28.                 }
  29.     }
  30. }
复制代码




作者: 月光海    时间: 2014-5-24 23:14
波涛 发表于 2014-5-24 22:45
因为你没有关闭流啊,记得流使用完了要关闭close()的,要释放资源。否则复制的东西仍然只是在内存中驻留而 ...

这个不是字符流而且没有用到缓冲流,不关资源也是有数据的
作者: 彭飞    时间: 2014-5-24 23:15
大概看了下,代码似乎没问题,
不过差了个finally     因为有个必然会做的动作  关闭。
作者: 张云刚    时间: 2014-5-24 23:25
没人回答吗,为什么 只有拷贝TXT  的文件,才可以成功,拷贝其余类型的,就失败 啊
作者: 波涛    时间: 2014-5-24 23:36
月光海 发表于 2014-5-24 23:14
这个不是字符流而且没有用到缓冲流,不关资源也是有数据的

嗯,你说的对,我记起来了,虽然可以不刷新,但是需要close关系统资源的。
你的代码我试过了,不关闭也不刷新是可以复制成功的(复制了一张图片),你检查一下你的文件是否占用或系统不可访问状态。。
真的不清楚了~




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