Java Convert File to Byte Array
Tags: Byte Array
In this Java tutorial we learn how to read a file to a byte[] array in Java programming language.
How to convert a File to byte[] array in Java
In Java we can use Files.readAllBytes() method to read all content of a file into byte[] array.
String fileName = "D:\\SimpleSolution\\data.txt";
Path filePath = Paths.get(fileName);
byte[] allBytes = Files.readAllBytes(filePath);
In the following Java example code we show you how to convert the file content into byte[] array in a Java application.
FileToByteArrayExample1.java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileToByteArrayExample1 {
public static void main(String... args) throws IOException {
String fileName = "D:\\SimpleSolution\\data.txt";
Path filePath = Paths.get(fileName);
byte[] allBytes = Files.readAllBytes(filePath);
System.out.println("File Bytes:");
for(byte b : allBytes) {
System.out.print(b);
}
String fileContent = new String(allBytes, StandardCharsets.UTF_8);
System.out.println("\nFile Content:");
System.out.println(fileContent);
}
}
File Bytes:
831051091121081013283111108117116105111110
File Content:
Simple Solution
Happy Coding 😊