先上代码 工具类实现:
package com.wang.chao.file.demo.read;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public final class FileReaderUtils {
/**
* 小文件读取,一次buffer缓冲,将全部文件内容读出,若不能一次读出则throw IOException,不执行数据读取操作。
*
* @param fileFullName 文件读取全路径名称
* @return
*/
public static byte[] readOnce(String fileFullName) throws IOException {
// open the file
File file = new File(fileFullName);
return readOnce(file);
}
/**
* 小文件读取,一次buffer缓冲,将全部文件内容读出,若不能一次读出则throw IOException,不执行数据读取操作。
*
* @param file
* @return
*/
public static byte[] readOnce(File file) throws IOException {
//check the file is Exists
checkFileExists(file);
// check the file is too long, if the file length is too long ,returned. because the byte array can not buffered.
// byte array bufferSize=file.lenght,and must between 0 and Integer_MAX_VALUE
if (file.length() > Integer.MAX_VALUE) {
System.err.println("file is too big ,not to read !");
throw new IOException(file.getName() + " is too big ,not to read ");
}
int _bufferSize = (int) file.length();
//定义buffer缓冲区大小
byte[] buffer = new byte[_bufferSize];
FileInputStream in &#