黑马程序员技术交流社区
标题:
自定义字节流缓冲区
[打印本页]
作者:
追逐
时间:
2014-3-26 09:26
标题:
自定义字节流缓冲区
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.BufferedOutputStream;
class MyInputStream
{
private InputStream is;
private byte[] by = new byte[1024*8];
private int pos = 0, count = 0; //pos是叫角标值,count是计数器
MyInputStream(InputStream is)
{
this.is = is;
}
public int myRead() throws IOException
{
if(count == 0)
{
count = is.read(by); //通过read方法把读取到的字节存储到byte数组中,并让count记录住数组个数(也就是数组长度)
if(count < 0)
return -1; //假如元素被取完了。就返回一个-1,并停止循环
pos = 0; //把元素存进来后要把角标值重新变成0;
byte b = by[pos]; //取出数组中的元素
count--;
pos++; //元素被取出后,让计数器自减。让角标值自增
return b & 255; //取出一个元素反出去一个元素
}
else if(count > 0) //如果计数器大于0.就一直读取。
{
byte b = by[pos]; //取出元素
count--;
pos++; //元素被取出后,让计数器自减。让角标值自增
return b & 255; //元素被取出后,让计数器自减。让角标值自增
}
return -1;
}
public void myClose() throws IOException //关闭资源函数
{
is.close();
}
}
class MyInputStreamDemo
{
public static void main(String[] args)
{
MyInputStream my = null;
BufferedOutputStream fos = null;
try
{
//关联一个文件
my = new MyInputStream(new FileInputStream("c:\\1.mp3"));
//定义一个写入的类
fos = new BufferedOutputStream(new FileOutputStream("c:\\2.mp3"));
int by = 0; //定义一个变量来记录被写入的字节
while((by = my.myRead()) != -1)
{
fos.write(by); //把字节写入新的文件中
}
}
catch (IOException e)
{
throw new RuntimeException("读取失败"); //捕获并处理异常
}
finally
{
try
{
if(my != null) //判断是否被实例化过
my.myClose();
}
catch (IOException e) //捕获并处理异常
{
throw new RuntimeException("读取关闭失败");
}
finally
{
try
{
if(fos != null) //判断是否被实例化过
fos.close();
}
catch (IOException e) //捕获并处理异常
{
throw new RuntimeException("写入关闭失败");
}
}
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2