本帖最后由 michaelchen 于 2013-3-20 23:34 编辑
- /*在C盘底下有个0.mp3的文件,通过字节流缓冲区实现对这个文件的复制*/
- import java.io.*;
- class MyBufferedInputStreamDemo
- {public static void main(String[] args)throws IOException
- {long start=System.currentTimeMillis();
- copy();
- long end=System.currentTimeMillis();
- System.out.println("复制使用了:"+(end-start)+"毫秒");
- }
- public static void copy()throws IOException
- { MyBufferedInputStream fis=new MyBufferedInputStream(new FileInputStream("c:\\0.mp3"));
- BufferedOutputStream fos=new BufferedOutputStream(new FileOutputStream("c:\\2.mp3"));
- int len=0;
- while((len=fis.myRead())!=-1)
- {fos.write(len);}
- fos.close();
- fis.myClose();
- }
- }
- class MyBufferedInputStream
- {private InputStream in;
- private byte[] buf=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(buf);
- if(count<0)
- return -1;
- pos=0;
- byte b=buf[pos];
- count--;
- pos++;
- return b&255; //为什么要与上255呢?
- }
- else if(count>0)
- { byte b=buf[pos];
- count--;
- pos++;
- return b&0xff;
- }
- return -1;
- }
- public void myClose()throws IOException
- { in.close();
- }
- }
复制代码 在上述代码的注释中,为什么要跟255相与呢?小弟实在费解 |