栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

38 字节缓冲流类 BufferedOutputStream & BufferedInputStream

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

38 字节缓冲流类 BufferedOutputStream & BufferedInputStream

  1. 继承自OutputStream
  2. 目的是在输出字节数据的时候,减少底层系统的调用.通过加入 字节缓冲区数组 的方式
  3. 构造方法:
	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];
    }
  1. 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 股份的公司豆腐干山豆根的

注意: 此处没有出现乱码.
为什么一次读取一个字节数组的时候,中文没有出现乱码呢?

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/677511.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号