黑马程序员技术交流社区

标题: 还是io流的问题 [打印本页]

作者: 魏亮    时间: 2012-10-12 16:50
标题: 还是io流的问题
本帖最后由 魏亮 于 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();
}
}


作者: 徐梦侠    时间: 2012-10-12 17:30
本帖最后由 徐梦侠 于 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;
}

作者: 魏亮    时间: 2012-10-15 09:39
徐梦侠 发表于 2012-10-12 17:30
public int myRead() throws IOException
{
    if (count==0)

恍然大悟,是我忽视了,if语句这几个是一个整体了,真是太感谢了




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2