java 分批读取文件_Java BufferedInputStream,BufferedOutputStream分批快速读取大文件

本文介绍了如何使用Java的BufferedInputStream和BufferedOutputStream类来分批读取和写入大文件,以提高读写效率。通过创建缓冲区,一次性处理多个字节,避免了频繁的磁盘操作,有效解决了大文件处理可能导致的内存问题和性能瓶颈。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首页 > 基础教程 > IO流 > OutputStream类

Java BufferedInputStream,BufferedOutputStream分批快速读取大文件

如果文件太大,一次性读取这个大文件的所有数据,内存可能装不下,但是如果每次只读一个字节数据,会耗时太慢。因此用BufferedInputStream一次读取1024*8个字节数据,用BufferedOutputStream放入缓冲区,分批读写。代码如下:

public static void main(String[] args) throws IOException

{

BufferedInputStream bufferInput = null;

BufferedOutputStream bufferOutput = null;

try

{

// 输入缓冲流

InputStream input = new FileInputStream(new File("c:\\100MB.txt"));

bufferInput = new BufferedInputStream(input);

// 输出缓冲流

OutputStream output = new FileOutputStream(new File("c:\\100MB_test.txt"));

bufferOutput = new BufferedOutputStream(output);

// 定义个8kb字节数组,作为缓冲区流

byte[] bytes = new byte[1024 * 8];

int len = 0;

while((len = bufferInput.read(bytes)) != -1)

{

bufferOutput.write(bytes, 0, len);

}

}

catch(IOException e)

{

}

finally

{

try

{

if(bufferInput != null)

{

bufferInput.close();

}

if(bufferOutput != null)

{

bufferOutput.close();

}

}

catch(IOException e)

{

}

}

}

版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值