JavaIO_Demo_BufferedInputStream

来源:互联网 发布:windows10切换苹果mac 编辑:程序博客网 时间:2024/06/05 16:18

这两天闲来无事,重温下JavaIO,并且做做小demo,写了一个文件copy的Demo,具体代码如下:

       public void copyFile(File fromFile, File toFile){try {InputStream is = new BufferedInputStream(new FileInputStream(fromFile));OutputStream os = new BufferedOutputStream(new FileOutputStream(toFile));byte[] bytes = new byte[1024];while(is.read(bytes) != -1) {os.write(bytes);}os.flush();is.close();os.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
    

写完以后一测试,就发现结果不如预想的那样,会出现copy出来的文件比原来的文件多一些内容。后来进行调试才发现,原来

os.write(bytes);
并不会把bytes清空,只是把读取的内容写进去,没覆盖掉的那些字节依然存在,因此在写出的时候又把它们再次输出来了。正确的做法是:

int len = is.read(bytes);while(len != -1){    os.write(bytes,0,len);    len = is.read(bytes);}