public static byte[] readFileToByteArray(File file) throws IOException
使用示例( Program.java ):
import org.apache.commons.io.FileUtils;
public class Program {
public static void main(String[] args) throws IOException {
File file = new File(args[0]); // assume args[0] is the path to file
byte[] data = FileUtils.readFileToByteArray(file);
...
}
}
16
Simple way to do it:
File fff = new File("/path/to/file");
FileInputStream fileInputStream = new FileInputStream(fff);
// int byteLength = fff.length();
// In android the result of file.length() is long
long byteLength = fff.length(); // byte count of the file-content
byte[] filecontent = new byte[(int) byteLength];
fileInputStream.read(filecontent, 0, (int) byteLength);
public static byte[] readBytes(InputStream inputStream) throws IOException {
byte[] b = new byte[1024];
ByteArrayOutputStream os = new ByteArrayOutputStream();
int c;
while ((c = inputStream.read(b)) != -1) {
os.write(b, 0, c);
}
return os.toByteArray();
}
呼叫者负责关闭流 .
8
// Returns the contents of the file in a byte array.
public static byte[] getBytesFromFile(File file) throws IOException {
// Get the size of the file
long length = file.length();
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
// File is too large
throw new IOException("File is too large!");
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
InputStream is = new FileInputStream(file);
try {
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
} finally {
is.close();
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
return bytes;
}
21 回答
Guava 有Files.toByteArray()为您提供 . 它有几个优点:
它涵盖了文件报告长度为0但仍有内容的角落情况
它经过高度优化,如果在尝试加载文件之前尝试读取大文件,则会出现OutOfMemoryException . (通过巧妙地使用file.length())
您不必重新发明轮子 .
另一种从文件中读取字节的方法
ReadFully 从当前文件指针开始,将此文件中的b.length个字节读入字节数组 . 此方法从文件中重复读取,直到读取所请求的字节数 . 此方法将一直阻塞,直到读取所请求的字节数,检测到流的末尾或抛出异常 .
从 JDK 7 您可以使用Files.readAllBytes(Path) .
例:
自JDK 7 - 一个班轮:
不需要外部依赖 .
Java 8的文档:http://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html
有人说,Apache Commons File Utils可能有你想要的东西
使用示例(
Program.java
):Simple way to do it:
如果要将字节读入预先分配的字节缓冲区,这个答案可能有所帮助 .
你的第一个猜测可能是使用InputStream read(byte[]) . 但是,这种方法存在一个缺陷,使其难以使用:即使没有遇到EOF,也无法保证阵列实际上会被完全填满 .
相反,看看DataInputStream readFully(byte[]) . 这是输入流的包装器,没有上述问题 . 此外,遇到EOF时抛出此方法 . 好多了 .
以下方法不仅将java.io.File转换为byte [],我还发现它是一种读取文件的最快方式,当测试许多不同的Java file reading methods时:
java.nio.file.Files.readAllBytes()
您也可以使用NIO api来完成它 . 只要总文件大小(以字节为单位)适合int,我就可以使用此代码执行此操作 .
我认为它使用MappedByteBuffer非常快 .
基本上你必须在内存中阅读它 . 打开文件,分配数组,并将文件中的内容读入数组 .
最简单的方法是这样的:
这有一些不必要的文件内容复制(实际上数据被复制三次:从文件到
buffer
,从buffer
到ByteArrayOutputStream
,从ByteArrayOutputStream
复制到实际结果数组) .您还需要确保在内存中只读取一定大小的文件(这通常取决于应用程序):-) .
您还需要在函数外部处理
IOException
.另一种方式是这样的:
这没有不必要的复制 .
FileTooBigException
是自定义应用程序异常 .MAX_FILE_SIZE
常量是一个应用程序参数 .对于大文件,您应该考虑使用流处理算法或使用内存映射(请参阅
java.nio
) .如果您没有Java 8,并同意我的意见,包括一个大型库以避免编写几行代码是一个坏主意:
呼叫者负责关闭流 .
我相信这是最简单的方法:
从文件中读取字节的最简单方法
使用与社区维基答案相同的方法,但更清晰和开箱即用的编译(如果您不想导入Apache Commons库,首选方法,例如在Android上):
这取决于最适合你的方式 . 生产环境 力明智,不要重新发明轮子并使用Apache Commons . 这是IOUtils.toByteArray(InputStream input) .
让我在不使用第三方库的情况下添加另一种解决方案 . 它重用了Scott(link)提出的异常处理模式 . 我把丑陋的部分移动到一个单独的消息中(我会隐藏在一些FileUtils类中;))