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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 魏亮 中级黑马   /  2012-10-12 16:50  /  1162 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 魏亮 于 2012-10-15 10:27 编辑

import java.io.*;
class  MyBufferedInputStreamDemo
{
public static void main(String[] args) throws IOException
{
  MyBufferedInputStream mybufis = new MyBufferedInputStream(new FileInputStream("1.mp3"));
  //BufferedInputStream bufis = new BufferedInputStream(new FileInputStream("1.mp3"));
  BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream("2.mp3"));
  int ch=0;
  
  while ((ch=mybufis.myRead())!=-1)
  {
   bufos.write(ch);
  }
  mybufis.myClose();
  bufos.close();
   }
}
class MyBufferedInputStream  
{
private InputStream is;
MyBufferedInputStream(InputStream is)
{
  this.is=is;
}
private int count=0,pos=0;
private byte[] buf = new byte[1024];
public int myRead() throws IOException
{
  if (count==0)
  {
   count=is.read(buf);
   pos=0;
   if (count<0)
   {
    return -1;
   }
/*  
byte b = buf[pos];
   pos++;
   count--;
   return b&255;
*/去掉这上边这个红色的代码的话复制的文件不能用,写上的话正常(写上后是老师的代码),为什么呢?我自己写的代码,也就是去掉上面红色代码后的代码,没有什么错误呀,就是没有立刻返回数组里的值而已呀,为什么不行??想不通呀!
  }
  else if (count>0)
  {
   byte b = buf[pos];
   pos++;
   count--;
   return b&255;
  }
  
  return -1;

}
public void myClose() throws IOException
{
  is.close();
}
}

评分

参与人数 1技术分 +1 收起 理由
刘芮铭 + 1 赞一个!

查看全部评分

2 个回复

倒序浏览
本帖最后由 徐梦侠 于 2012-10-12 17:31 编辑

public int myRead() throws IOException
{
    if (count==0)
    {
      count=is.read(buf);
      System.out.println(count);
      pos=0;
      if (count<0)
      {
       return -1;
      }
      
    /*byte b = buf[pos];
    pos++;
    count--;
    return b&255;*/
   
    /*要是去掉上面这段代码,那么这段if代码块就没有返回语句,
      * if执行之后明显不再执行else中的语句了。所以就会直接执行return -1。
      * 返回-1后上面的while循环也就结束了,所以最后什么复制文件失败
    */
    }
    else if (count>0)
    {
      byte b = buf[pos];
      pos++;
      count--;
      return b&255;
    }
   
    return -1;
}

评分

参与人数 1技术分 +1 收起 理由
刘芮铭 + 1 赞一个!

查看全部评分

回复 使用道具 举报
徐梦侠 发表于 2012-10-12 17:30
public int myRead() throws IOException
{
    if (count==0)

恍然大悟,是我忽视了,if语句这几个是一个整体了,真是太感谢了
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马