This article shows a few ways to save a byte[] into a file.
For JDK 1.7 and above, the NIO Files.write is the simplest solution to save byte[] to a file.
// bytes = byte[]
Path path = Paths.get("/path/file");
Files.write(path, bytes);
FileOutputStream is the best alternative.
try (FileOutputStream fos = new FileOutputStream("/path/file")) {
fos.write(bytes);
//fos.close // no need, try-with-resources auto close
}
If we have Apache Commons IO, try FileUtils.
FileUtils.writeByteArrayToFile(new File("/path/file"), bytes);
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
1. Save byte[] to a file.
The below example reads a file and converts the data into a byte[]. Later, we save the byte[] into another file.
package com.mkyong.io.howto;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ByteToFile {
public static void main(String[] args) {
try {
// tested with character data and binary data
// file to bytes[]
byte[] bytes = Files.readAllBytes(Paths.get("/home/mkyong/test/file.txt"));
// save byte[] to a file
writeBytesToFile("/home/mkyong/test/file2.txt", bytes);
writeBytesToFileNio("/home/mkyong/test/file3.txt", bytes);
writeBytesToFileApache("/home/mkyong/test/file4.txt", bytes);
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
//JDK 7 - FileOutputStream + try-with-resources
private static void writeBytesToFile(String fileOutput, byte[] bytes)
throws IOException {
try (FileOutputStream fos = new FileOutputStream(fileOutput)) {
fos.write(bytes);
}
}
//JDK 7, NIO, Files.write
private static void writeBytesToFileNio(String fileOutput, byte[] bytes)
throws IOException {
Path path = Paths.get(fileOutput);
Files.write(path, bytes);
}
// Apache Commons IO
private static void writeBytesToFileApache(String fileOutput, byte[] bytes)
throws IOException {
FileUtils.writeByteArrayToFile(new File(fileOutput), bytes);
}
}
Download Source Code
$ git clone https://github.com/mkyong/core-java
$ cd java-io
is there any way or api to convert Image or any type of file byte into PDF
Try below PDF libraries.
https://pdfbox.apache.org/
https://itextpdf.com/en
thank you
then how to read it back as byte[] variable??
byte[] bytes = Files.readAllBytes(Paths.get("/home/mkyong/test/file.txt"));How to remove or update the metadata/Exif/Property from Base64/byte Array file Android?
thanks ..mykong,…it worked for me..
I need create the file object can not exist on the machine, only in memory, how to do?
Thank you