这两天闲来无事,重温下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);
}