我如何将java.io.File转换为字节[]?
当前回答
JDK 7以来的一行代码:
byte[] array = Files.readAllBytes(Paths.get("/path/to/file"));
不需要外部依赖。
其他回答
从文件中读取字节的另一种方法
Reader reader = null;
try {
reader = new FileReader(file);
char buf[] = new char[8192];
int len;
StringBuilder s = new StringBuilder();
while ((len = reader.read(buf)) >= 0) {
s.append(buf, 0, len);
byte[] byteArray = s.toString().getBytes();
}
} catch(FileNotFoundException ex) {
} catch(IOException e) {
}
finally {
if (reader != null) {
reader.close();
}
}
正如有人所说,Apache Commons File Utils可能有您正在寻找的东西
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);
...
}
}
可以像这样简单地完成(Kotlin版本)
val byteArray = File(path).inputStream().readBytes()
编辑:
我读过readBytes方法的文档。它说:
将此流完全读入字节数组。 注意:关闭这个流是调用者的责任。
因此,为了能够关闭流,同时保持一切干净,使用以下代码:
val byteArray = File(path).inputStream().use { it.readBytes() }
感谢@user2768856指出这一点。
Guava有Files.toByteArray()可以提供给您。它有几个优点:
它涵盖了文件报告长度为0但仍然有内容的极端情况 它是高度优化的,如果在加载文件之前试图读入一个大文件,你会得到一个OutOfMemoryException。(通过巧妙地使用file.length()) 你没必要白费力气。
JDK 7以来的一行代码:
byte[] array = Files.readAllBytes(Paths.get("/path/to/file"));
不需要外部依赖。
推荐文章
- 如何在java中格式化持续时间?(如格式H:MM:SS)
- urlencoder .encode(字符串)已弃用,我应该使用什么代替?
- javax.transaction.Transactional vs . org.springframework.transaction.annotation.Transactional
- Java 8接口方法中不允许“同步”的原因是什么?
- 如何找到Java堆大小和内存使用(Linux)?
- 使用Enum实现单例(Java)
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 如何在Java中按两个字段排序?
- 文件之间的差异。路径中的分隔符和斜杠
- 在方法参数中使用NotNull注释
- Spring MVC中处理可选参数的@RequestParam
- Tomcat:如何查找正在运行的Tomcat版本?
- 如何在Python中连接文本文件?