黑马程序员技术交流社区
标题:
自定义字节缓冲流复制文件问题
[打印本页]
作者:
于启会
时间:
2012-9-9 23:14
标题:
自定义字节缓冲流复制文件问题
本帖最后由 于启会 于 2012-9-10 00:27 编辑
import java.io.*;
public class MyBufferedInputStream{
private InputStream in;
private byte[] buf=new byte[1024]; //定义一个byte类型数组。
private int pos=0,count=0; //定义一个下标器,一个计数器
public MyBufferedInputStream(InputStream in){
this.in=in;
}
public int MyReadLine() throws IOException{
if(count==0){
count=in.read(buf);
if(count<0){
pos=0;
return -1;
}
byte b=buf[pos];
count--;
pos++;
return b&255;
}
else if(count>0){
byte b =buf[pos];
count--;
pos++;
return b&255;
}
return -1;
}
public void Myclose() throws IOException{
this.in.close();
}
}
import java.io.*;
public class BufferedStreamDemo{
public static void main(String arg[]){
try{
FileInputStream fis = new FileInputStream("E:\\<a href="file://\\IO">IO</a>流<a href="file://\\music\\">\\music\\</a>柴米油盐酱醋茶.mp3");
FileOutputStream fos=new FileOutputStream("E:\\<a href="file://\\IO">IO</a>流\\哈哈.mp3");
copy_1(fis,fos);
}catch(IOException e){
System.out.println(e.toString());
}
}
public static void copy_1(InputStream input,OutputStream out){
MyBufferedInputStream bis=new MyBufferedInputStream(input);
BufferedOutputStream bos=new BufferedOutputStream(out);
try{
int temp=0;
while((temp=bis.MyReadLine())!=-1){
bos.write(temp);
}
}catch(IOException e){
System.out.println(e.toString());
}finally{
try{
if(bos!=null){
bos.close();
}
if(bis!=null){
bis.Myclose();
}
}catch(IOException e){
System.out.println(e.toString());
}
}
}
}
运行能复制,但是复制的文件大小比原文件大小很多,到底是哪里出了错?
复制代码
作者:
李菁
时间:
2012-9-9 23:29
public int MyReadLine() throws IOException{
11.
12. if(count==0){
13. count=in.read(buf);
14.
15. if(count<0){
16. pos=0;
把这句话放到if外边,if是判断是否取到最后了。
pos=0;这句话代表每次往里面重装数据,pos这个指针都要归0
17. return -1;
18. }
19. byte b=buf[pos];
20. count--;
21. pos++;
22. return b&255;
23. }
24. else if(count>0){
25. byte b =buf[pos];
26. count--;
27. pos++;
28. return b&255;
29. }
30. return -1;
31. }
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2