Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File to byte[] in Java

Tags:

java

file-io

How do I convert a java.io.File to a byte[]?

like image 474
Ben Noland Avatar asked May 13 '09 16:05

Ben Noland


People also ask

What does byte [] do in Java?

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.

Can you print [] byte?

You can simply iterate the byte array and print the byte using System. out. println() method.

How do I write a byte array to a file?

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.

How do I create a byte file?

write(bytes, new File(path)); With Apache Commons: FileUtils. writeByteArrayToFile(new File(path), bytes);


1 Answers

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()); 
like image 56
12 revs, 11 users 24% Avatar answered Oct 02 '22 04:10

12 revs, 11 users 24%