原文链接:Writing byte[] to a File in Java
1. Overview 概述
In this quick tutorial, we're going to learn several different ways to write a Java byte array to a file. We'll start at the beginning, using the Java IO package. Next, we'll look at an example using Java NIO. After that, we'll use Google Guava and Apache Commons IO.
在这篇介绍中,让我们来一起学习在Java中把byte数组写入文件的几种方式吧。先使用JavaIO包中的类,接着使用JavaNIO包的类,之后使用Google Guava和Apache Commons IO包的类来实现
2. Java IO
Java's IO package has been around since JDK 1.0 and provides a collection of classes and interfaces for reading and writing data.
JavaIO包是从JDK1.0开始的,它提供了一堆的类和接口来读取写入数据。
Let's use a FileOutputStream to write the image to a file:
首先使用FileOutputStream类来把图片字节数组写为图片文件:
File outputFile = tempFolder.newFile("outputFile.jpg");
try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
outputStream.write(dataForWriting);
}
We open an output stream to our destination file, and then we can simply pass our byte[] dataForWriting to the write method. Note that we're using a try-with-resources block here to ensure that we close the OutputStream in case an IOException is thrown.
首先创建