package cn.heima.stream;
/*
演示mp3的复制。通过缓冲区。
BufferedOutputStream
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_2()throws IOException
{
MyBufferedInputStream bufis = new MyBufferedInputStream(new FileInputStream("0.mp3"));
BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream("2.mp3"));
int by = 0;
System.out.println("第一个字节:"+bufis.myRead());
while((by=bufis.myRead())!=-1)
{
bufos.write(by);
}
bufos.close();
bufis.myClose();
}
//通过字节流的缓冲区完成复制。
public static void copy_1()throws IOException
{
BufferedInputStream bufis = new BufferedInputStream(new FileInputStream("0.mp3"));
BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream("1.mp3"));
int by = 0;
while((by=bufis.read())!=-1)
{
bufos.write(by);
}
bufos.close();
bufis.close();
}
}
class MyBufferedInputStream
{
private InputStream in;
private byte[] buf = new byte[1024*4];
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;
pos = 0;
byte b = buf[pos];
count--;
pos++;
return b&255;
}
else if(count>0)
{
byte b = buf[pos];
count--;
pos++;
System.out.println("b:"+b);
System.out.println("b&0xff:"+ (b&0xff) );
return b&0xff;
}
return -1;
}
public void myClose()throws IOException
{
in.close();
}
}
提问:bufos.write(by); 其中的by是经过提升的,比如byte型的负数经过 &0xFF 运算后会提升为整形的正数,也就是返回的 int的 by,本来时byte型的负数,提升为int的by,再将by写入,为什么没有导致乱码呢??
|