ReadFile2ByteArrayTest

本文提供了一个使用Java FileInputStream从指定路径读取文件并将其内容转换为字节数组的示例。通过不断读取直至文件末尾,该示例展示了如何处理文件读取过程中的缓冲区溢出。

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

package com.ghca.policeintf.test;

import java.io.FileInputStream;
import java.io.IOException;

/**
* Created by DUDU on 2017/11/2.
*/
public class ReadFile2ByteArrayTest {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("D:\\32位系统移植过来的文件\\1`.rar");
byte[] buffer = new byte[1024];
int totalReadCount = 0;
while(true) {
int remaining = buffer.length - totalReadCount;
// if (remaining > 0) {
// int currentReadCount = fis.read(buffer,totalReadCount,remaining);
// if (currentReadCount > 0) {
// totalReadCount = totalReadCount + currentReadCount;
// } else {
// break;
// }
// } else {//扩容buffer
// byte[] newBuffer = new byte[buffer.length * 2];
// System.arraycopy(buffer,0,newBuffer,0,totalReadCount);
// buffer = newBuffer;
// }
if (remaining <= 0) {//先扩容buffer
byte[] newBuffer = new byte[buffer.length * 2];
System.arraycopy(buffer,0,newBuffer,0,buffer.length);
buffer = newBuffer;
// remaining = buffer.length - totalReadCount;
continue;
}
int currentReadCount = fis.read(buffer,totalReadCount,remaining);
if (currentReadCount > 0) {
totalReadCount = totalReadCount + currentReadCount;
} else {
break;
}
}
System.out.println("总共读取字节数:" + totalReadCount);
System.out.println("buffer大小:" + buffer.length);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值