码迷,mamicode.com
首页 > 其他好文 > 详细

自定义InputStream里的read()方法

时间:2014-12-20 19:34:51      阅读:572      评论:0      收藏:0      [点我收藏+]

标签:

------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、ios培训、.Net培训</a>、期待与您
交流!------
通过对IO的学习,我们知道InputStream里面有一个非常使用的方法:read()方法通过学习发现其底层用到了数组,那么思考
到自己定义一个myRead()来达到同样的效果。
代码如下:

import java.io.*;
public class byteCopyMp3 
{
public static void main(String[] args)throws IOException
{
copy_1();
}
public static void copy_1() throws IOException
{
MyBufferedInputStream bufis=new MyBufferedInputStream(new FileInputStream("D:\\KuGou\\张国荣 - 当爱已
成往事【霸王别姬】.mp3"));
BufferedOutputStream bufos=new BufferedOutputStream(new FileOutputStream("d:\\pos.mp3"));
int by=0;
while((by=bufis.myRead())!=-1)
{
bufos.write(by);
}
bufis.myClose();
bufos.close();
}
}
class MyBufferedInputStream
{
private InputStream in;
private byte[] by=new byte[1024];
private int pos=0,count=0;
MyBufferedInputStream(InputStream in)
{
this.in=in;
}
public int myRead() throws IOException
{
if(count==0)
{
count=in.read(by);
if(count<0)
return -1;
pos=0;
byte b=by[pos];
pos++;
count--;
return b;
}
else if(count>0)
{
byte b=by[pos];
pos++;
count--;
return b;
}
return -1;
}
public void myClose()throws IOException
{
in.close();
}

运行结果:
原文件属性:技术分享


复制后的文件:技术分享

比较发现:原文件比复制后的文件大的多,说明没有复制成功。问题出在哪里呢?
通过查阅资料:原来InputStream里面的read方法封装了一些“&操作”来确保数据的完整性。
虽然代码没有问题,但是我们定义的read方法是Int类型的返回值,但字节数组实际操作的是字节。
如上面的return b;这里的b就是byte类型的。那么将b&255即可,将上面return b替换成return b&255
看结果:
图片
复制完成了!


------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、ios培训、.Net培训</a>、期待与您
交流!------

 

自定义InputStream里的read()方法

标签:

原文地址:http://www.cnblogs.com/z-k47/p/4175752.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!