How do I convert a java.io.File
to a byte[]
?
A byte in Java is 8 bits. It is a primitive data type, meaning it comes packaged with Java. Bytes can hold values from -128 to 127. No special tasks are needed to use it; simply declare a byte variable and you are off to the races.
You can simply iterate the byte array and print the byte using System. out. println() method.
In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file.
write(bytes, new File(path)); With Apache Commons: FileUtils. writeByteArrayToFile(new File(path), bytes);
From JDK 7 you can use Files.readAllBytes(Path)
.
Example:
import java.io.File; import java.nio.file.Files; File file; // ...(file is initialised)... byte[] fileContent = Files.readAllBytes(file.toPath());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With