黑马程序员技术交流社区
标题:
用自己写的缓冲方法复制文件的时候总是缺少一部分
[打印本页]
作者:
黑马_宋超
时间:
2012-8-14 10:01
标题:
用自己写的缓冲方法复制文件的时候总是缺少一部分
本帖最后由 Dreamer 于 2012-8-14 10:03 编辑
用这个自定义的缓冲方法来复制文件的时候,每次文件总有一小部分没有复制成功,请问下这是为什么呢??谢谢拉
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class MyBufferedDemo {
public static void main(String[] args) {
try {
MyBuffered mbf = new MyBuffered(new FileInputStream("d:/hehe.jpg"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("d:/haha.jpg"));
int x= 0;
while((x = mbf.myRead()) != -1) {
try {
bos.write(x);
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
class MyBuffered {
private FileInputStream fir;
private int count = 0,pos = 0;
private byte[] buf = new byte[1024];
public MyBuffered(FileInputStream fir) {
this.fir = fir;
}
public int myRead() {
int b = 0;
if(count == 0) {
try {
count = fir.read(buf);
pos = 0;
if(count > 0 ) {
b = buf[pos];
pos++;
count--;
return b &255;
}
if(count == -1) {
return -1;
}
} catch (IOException e) {
e.printStackTrace();
}
}
else if(count > 0 ) {
b = buf[pos];
pos++;
count--;
return b&255;
}
if(count == -1) {
return -1;
}
return -1;
}
}
复制代码
作者:
黑马_宋超
时间:
2012-8-14 11:03
好吧,原来我忘记关闭流或者刷新流了{:soso_e109:}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2