/*
演示mp3的复制,通过缓冲区。
BufferedOutoutStream
BufferedInputStream
*/
import java.io.*;
class CopyMp3
{
public static void main(String[] args) throws IOException
{
long start = System.currentTimeMillis();
copy_2();
long end = System.currentTimeMillis();
System.out.println((end-start)+"毫秒");
}
//通过字节流的缓冲区完成复制。
public static void copy_1()throws IOException
{
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\0.mp3"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("C:\\1.mp3"));
int by = 0;
while((by=bis.read())!=-1)
{
bos.write(by);
}
bos.close();
bis.close();
}
public static void copy_2()throws IOException
{
MyBufferedInputStream bis = new MyBufferedInputStream(new FileInputStream("C:\\0.mp3"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("C:\\1.mp3"));
int by = 0;
//System.out.println("第一个字节:"+bis.myRead());
while((by=bis.myRead())!=-1)
{
bos.write(by);
}
bos.close();
bis.myClose();
}
}
class MyBufferedInputStream
{
private InputStream in;
private byte[] buf = new byte[1024*1024];
private int pos = 0,count = 0;
MyBufferedInputStream(InputStream in)
{
this.in = in;
}
//一次读一个字节,从缓冲(字节数组)获取。
public int myRead()throws IOException
{
//通过in对象读取硬盘上数据,并存储buf中。
if(count==0)
{
count = in.read(buf);
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
{
in.close();
}
}
/*
11111111 -->提升了一个int类型 那还不是-1吗?是-1的原因是因为在8个1前面补的是1导致的。
那么我么只要在前面补0,即可以保留原字节数据不变,又可以避免-1的出现。只要&255即可!!
*/
****在&255前可以编译运行,但是&之后跑出ArrayOutOfBoundsException异常,详情看附件,求解问题出在哪了?
|
|