本帖最后由 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;
-
- }
- }
复制代码 |
|