A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 韩俊杰 中级黑马   /  2013-1-11 20:45  /  1340 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 韩俊杰 于 2013-1-14 12:47 编辑
  1. package io;
  2. import java.io.*;

  3. class MyBufferedInputStream{
  4. private InputStream in;
  5. private byte[] buf=new byte[1024];
  6. private int pos=0,count=0;
  7. MyBufferedInputStream(InputStream in){
  8. this.in=in;
  9. }
  10. //一次读一个字节,从缓冲区(字节数组)获取
  11. public int myRead()throws IOException{
  12. //通过in对象读取硬盘上的数据,并存储到buf中
  13. if(count==0){
  14. count=in.read(buf);
  15. if(count<0)
  16. return -1;
  17. pos=0;
  18. byte b=buf[pos];
  19. count--;
  20. pos++;
  21. return b&255;
  22. }else if(count>0){
  23. byte b=buf[pos];
  24. count--;
  25. pos++;
  26. return b&0xff;

  27. }
  28. return -1;


  29. }

  30. public void myClose()throws IOException{
  31. in.close();
  32. }
  33. }


  34. public class CopyMp3Demo {
  35. public static void main(String[] args)throws IOException {

  36. long start=System.currentTimeMillis();
  37. copy();
  38. long end=System.currentTimeMillis();
  39. System.out.println((end-start)+"毫秒");


  40. }
  41. //通过字节流缓冲区进行复制
  42. public static void copy()throws IOException{
  43. MyBufferedInputStream bis=new MyBufferedInputStream(new FileInputStream("1.mp3"));
  44. BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("2.mp3"));

  45. int ch=0;
  46. while((ch=bis.myRead())!=-1){
  47. bos.write(ch);
  48. }
  49. bis.myClose();
  50. bos.close();
  51. }

  52. }
复制代码
b&255,为什么b&255拷贝图片就成功了?请各位大神指点

评分

参与人数 1技术分 +1 收起 理由
冯海霞 + 1

查看全部评分

3 个回复

倒序浏览
黑马吕世成 来自手机 中级黑马 2013-1-13 02:41:07
沙发
因为此时b的二进制值不等于负一啊。之所以返回一个int值,就是为了避免对到的字节刚好对应的值为负一,而导致读去数据失败。能明白不?毕老师视频也有讲到这个。来自: Android客户端
回复 使用道具 举报
因为字节文件可能出现1111-1111的情况 //1111-1111十进制是-1
因为b是byte类型的,被提升为int类型的//public int myRead()
            所以变为1111-1111-1111-1111-1111-1111-1111-1111,为了避免1111-1111前补1带来的影响,
            所以   &0000—0000—0000—0000—0000—0000—1111-1111//十进制255,
所以就避免了做错误判断。
回复 使用道具 举报
知道了,谢谢各位大神,还需要继续努力
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马