BufferedInputStream使用详解

下面的例子演示如何使用BufferedInputStream类读取文本文件内容。

首先需要声明一个byte数组作为buffer,然后循环将文本内容循环读入到buffer中,并将buffer转换为字符串,打印到控制台。

/**
*
* @author outofmemory.cn
*/
public class Main {

    /**
     * 从文件中读取文本
*/
public void readFromFile(String filename) {

        BufferedInputStream bufferedInput = null;
        byte[] buffer = new byte[1024];

        try {

            //创建BufferedInputStream 对象
bufferedInput = new BufferedInputStream(new FileInputStream(filename));

            int bytesRead = 0;

            //从文件中按字节读取内容,到文件尾部时read方法将返回-1
            while ((bytesRead = bufferedInput.read(buffer)) != -1) {

                //将读取的字节转为字符串对象
String chunk = new String(buffer, 0, bytesRead);
                System.out.print(chunk);
            }

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            //关闭 BufferedInputStream
            try {
                if (bufferedInput != null)
                    bufferedInput.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * @param args 命令行参数
*/
public static void main(String[] args) {
        new Main().readFromFile("myFile.txt");
    }
}

使用方法

  BufferedInputStream继承于FilterInputStream,提供缓冲输入流功能。缓冲输入流相对于普通输入流的优势是,它提供了一个缓冲数组,每次调用read方法的时候,它首先尝试从缓冲区里读取数据,若读取失败(缓冲区无可读数据),则选择从物理数据源(譬如文件)读取新数据(这里会尝试尽可能读取多的字节)放入到缓冲区中,最后再将缓冲区中的内容部分或全部返回给用户.由于从缓冲区里读取数据远比直接从物理数据源(譬如文件)读取速度快。

方法介绍

  BufferedInputStream提供的API如下:

//构造方法
BufferedInputStream(InputStream in)
BufferedInputStream(InputStream in, int size)

//下一字节是否可读
synchronized int     available()
//关闭
void     close()
//标记, readlimit为mark后最多可读取的字节数
synchronized void     mark(int readlimit)
//是否支持mark, true
boolean     markSupported()
//读取一个字节
synchronized int     read()
//读取多个字节到b
synchronized int     read(byte[] b, int off, int len)
//重置会mark位置
synchronized void     reset()
//跳过n个字节
synchronized long     skip(long n)

 

使用示例

public void testBufferedInput() {
    try {
        /**
         * 建立输入流 BufferedInputStream, 缓冲区大小为8
         * buffer.txt内容为
         * abcdefghij
         */
        InputStream in = new BufferedInputStream(new FileInputStream(new File("buff.txt")), 8);
        /*从字节流中读取5个字节*/
        byte [] tmp = new byte[5];
        in.read(tmp, 0, 5);
        System.out.println("字节流的前5个字节为: " + new String(tmp));
        /*标记测试*/
        in.mark(6);
        /*读取5个字节*/
        in.read(tmp, 0, 5);
        System.out.println("字节流中第6到10个字节为: " +  new String(tmp));
        /*reset*/
        in.reset();
        System.out.printf("reset后读取的第一个字节为: %c" , in.read());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

  运行结果如下:

字节流的前5个字节为: abcde
字节流中第610个字节为: fghij
reset后读取的第一个字节为: f



使用BufferedInputStream和BufferedOuputStream读写图片

 

使用方式和FileInputStrem和FileOutputStream基本一致:

 

[java] view plain copy
 
  1. package org.example.io;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.FileOutputStream;  
  8.   
  9. public class TestBufferedString {  
  10.   
  11.     public static void main(String[] args) throws Exception {  
  12.         // 指定要读取文件的缓冲输入字节流  
  13.         BufferedInputStream in = new BufferedInputStream(new FileInputStream("F:\\test.jpg"));  
  14.         File file = new File("E:\\test.jpg");  
  15.         if (file != null) {  
  16.             file.createNewFile();  
  17.         }  
  18.         // 指定要写入文件的缓冲输出字节流  
  19.         BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));  
  20.         byte[] bb = new byte[1024];// 用来存储每次读取到的字节数组  
  21.         int n;// 每次读取到的字节数组的长度  
  22.         while ((n = in.read(bb)) != -1) {  
  23.             out.write(bb, 0, n);// 写入到输出流  
  24.         }  
  25.         out.close();// 关闭流  
  26.         in.close();  
  27.     }  
  28.   
  29. }  
posted @   有梦就能实现  阅读(83223)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-03-29 mysql中间件研究(tddl atlas cobar sharding-jdbc)
2017-03-29 数据库Sharding的基本思想和切分策略
2017-03-29 数据库分库分表(sharding)系列(一) 拆分实施策略和示例演示
2017-03-29 利用Sharding-Jdbc实现分表
2017-03-29 java 读写分离
2017-03-29 在应用层通过spring特性解决数据库读写分离
2017-03-29 JAVA-mysql读写分离插件介绍
点击右上角即可分享
微信分享提示