黑马程序员技术交流社区

标题: 关于io流问题,流已经关了为嘛还在疯狂读写啊 [打印本页]

作者: 徐君    时间: 2013-11-21 14:34
标题: 关于io流问题,流已经关了为嘛还在疯狂读写啊
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class test3 {

        public static void main(String[] args)
        {
                BufferedOutputStream bo=null;
                BufferedInputStream bi=null;
                try
                {
                        bi=new BufferedInputStream(new FileInputStream("e:\\Demo.txt"));
                        bo=new BufferedOutputStream(new FileOutputStream("e:\\Demo_copy2.txt"));
                        byte[] buf=new byte[1024];
                        int len=bi.read(buf);
                        while(len!=-1)
                        {
                                bo.write(buf, 0,buf.length);
                                bo.flush();
                        }
                }
                catch(IOException e)
                {
                        System.out.println("你的路径是错误的!");
                       
                }
                finally
                {
                        try
                        {
                                bi.close();
                        }
                        catch(IOException e)
                        {
                                System.out.println("读取流关闭失败!");
                        }
                        try
                        {
                                bo.close();
                        }
                        catch(IOException e)
                        {
                                System.out.println("输入刘关闭失败!");
                        }
                        System.out.println("复制成功!");
                }

        }
       

}


作者: 汪洋大海    时间: 2013-11-21 15:09
本帖最后由 汪洋大海 于 2013-11-21 15:19 编辑

根本原因是因为read没有在循环中。
停不下来是因为,while表达示会一直为true。因为buf数组中会一直有数据。
int len=bi.read(buf);
while(len!=-1)
这两名话改成
int len = 0;
while((len=bi.read(buf)!=-1))
就行了。
还有一个地方也写错了。
bo.write(buf, 0,len);
这样写才是对的。
只写数组中的有效字节。

作者: 汪洋大海    时间: 2013-11-21 15:22
汪洋大海 发表于 2013-11-21 15:09
根本原因是因为read没有在循环中。
停不下来是因为,while表达示会一直为true。因为buf数组中会一直有数据 ...

还可以把
bo.write(buf, 0,buf.length);
bo.flush();
改成
bo.write(buf, 0,len);
bo.flush();
len=bi.read(buf);




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