- 继承自OutputStream
- 目的是在输出字节数据的时候,减少底层系统的调用.通过加入 字节缓冲区数组 的方式
- 构造方法:
protected OutputStream out;
public FilterOutputStream(OutputStream out) {
this.out = out;
}
public BufferedOutputStream(OutputStream out, int size) {
super(out);
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];
}
- BufferedInputStream字节缓冲流
public BufferedInputStream(InputStream in) {
this(in, DEFAULT_BUFFER_SIZE);
}
public BufferedInputStream(InputStream in, int size) {
super(in);
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];
}
注意: 以上字节缓冲流的类只提供缓冲区,流的read,write还是依靠基本的FileInputStream,FileOutputStream
4. 使用字节缓冲流进行输出:
public static void main(String[] args) throws Exception{
FileOutputStream fos = new FileOutputStream("D:\wjh\java.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
//写数据
bos.write("hello buffered".getBytes());
bos.close();
}
5 使用BufferedInputStream读取数据
方式一: 一次读取一个字节
public static void main(String[] args) throws Exception{
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\wjh\java.txt"));
int len;
while ((len = bis.read()) != -1){
System.out.print((char) len);
}
}
hello buffered è‚¡ä»½çš„å ¬å¸è±†è å¹²å±±è±†æ ¹çš„
此处中文出现了乱码.因为测试文件java.txt中存在中文
方式二: 一次读取一个字节数组
public static void main(String[] args) throws Exception{
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\wjh\java.txt"));
byte[] bytes = new byte[1024];
int len;
while ((len = bis.read(bytes)) != -1){
System.out.print(new String(bytes,0,len));
}
}
hello buffered 股份的公司豆腐干山豆根的
注意: 此处没有出现乱码.
为什么一次读取一个字节数组的时候,中文没有出现乱码呢?



