Java NIO + ByteArrayOutputStream 读取文件数据并转为字节数组
package com.zhexiao.kafka.component;import org.apache.kafka.common.utils.Bytes;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;import java.io.*;i
·
package com.zhexiao.kafka.component;
import org.apache.kafka.common.utils.Bytes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* 读取文件数据
*
* @author zhe.xiao
* @date 2020/09/11
* @description 上传图片保存到本地
*/
@Component
public class ReadFile {
private static final Logger log = LoggerFactory.getLogger(ReadFile.class);
/**
* 读取文件并转为字节数组
*
* @param filepath
* @return 字节数组
*/
public byte[] readBinary(String filepath) {
File file = new File(filepath);
if (!file.exists()) {
log.error("文件不存在, filepath={}", filepath);
return Bytes.EMPTY;
}
try (
FileInputStream fis = new FileInputStream(filepath);
FileChannel fisChannel = fis.getChannel();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream((int) fisChannel.size());
) {
//分配缓冲区,设定每次读的字节数
ByteBuffer byteBuffer = ByteBuffer.allocate(4);
//读取数据
int len = 0;
while ((len = fisChannel.read(byteBuffer)) > 0) {
//上面把数据写入到了buffer,所以可知上面的buffer是写模式,调用flip把buffer切换到读模式,读取数据
byteBuffer.flip();
byteArrayOutputStream.write(byteBuffer.array(), 0, len);
byteBuffer.clear();
}
return byteArrayOutputStream.toByteArray();
} catch (Exception e) {
log.info("读取文件异常,e={}", e.getMessage());
return Bytes.EMPTY;
}
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)