文章目录
public abstract int read()throws IOExceptior从输入流中读取数据的下一个字节。返回0到255范围内的int字节值。如果因为已经到达流末尾而没有可用的字节,则返回值-1,数据可用、检测到流末尾或者抛出异常前,此方法一直阻塞。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| import java.io.*; class MyBufferedInputStream//自定义BuffereedInputStream类 { //装饰设计模式 private InputStream in; private byte[] buffer=new byte[1024]; private int count=0; private int pos=0; MyBufferedInputStream(InputStream in)//构造器 { this.in=in; } //模拟read方法 public int Myread()throws IOException { if(count==0) { count=in.read(buffer); //计数器记录通过public int read(byte[] b)方法存 //到数组缓冲区的数据的总字节数 pos=0;//如果计数器为0,则位置指针归零 if(count<0) return -1; } byte b=buffer[pos]; pos++; count--; //return b&255; return b&0xff;//关键在此,为什么要返回b和0xff的与呢? } //重写close方法 public void Myclose()throws IOException { in.close(); } } class Demo { //为了代码简洁,这里直接抛IO异常了,正确的做法是try,catch。 public static void main(String[] args)throws IOException { long start=System.currentTimeMillis(); Copy(); long end=System.currentTimeMillis(); System.out.println("runtime:"+(end-start)+"ms");//获取运行时间 } public static void Copy()throws IOException//拷贝功能封装在Copy方法体里面 { MyBufferedInputStream mb=new MyBufferedInputStream(new FileInputStream("3.mp3")); BufferedOutputStream bo=new BufferedOutputStream(new FileOutputStream("copy_1.mp3")); int ch=0; while((ch=mb.Myread())!=-1) bo.write(ch); bo.close(); mb.Myclose(); } }
|
为什么myread方法返回的是b和0xff的与呢?
read方法返回int的原因:
首先我们知道,mp3文件全部为二进制数据组成的。这就有一个问题,如果恰好read方法读取的字节是1111-1111(即byte型的-1)怎么办?这时候返回的是-1.那这样的话Copy方法中的while循环就会停止,也就没有复制。
解决方法:
我们伟大的程序员采取了一个办法.那就是返回int型
1111-1111如果变成int型的话,应该是int型的-1,即11111111-11111111-11111111-11111111,
我们将int型的-1和0xff &一下,
11111111 11111111 -11111111 -11111111
&00000000-00000000-00000000-11111111(int型的255)
00000000-00000000-00000000-11111111
这样返回的就是有效字节了,而且不会出现-1的情况。
read方法做了一个类型提升,其实write方法每次也是强转,将int型的数据再转换为byte,这样获取的还是有效字节。
作者:rowandjj
来源:CSDN
原文:https://blog.csdn.net/chdjj/article/details/8577861
版权声明:本文为博主原创文章,转载请附上博文链接!