English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input Output (I/O)/O)

Java Reader/Writer

Java Other Topics

Java program converts a file object (File) to a byte array (byte[]) and vice versa

Comprehensive Java Examples

In this program, you will learn how to convert a File object to a byte [] in Java, and vice versa.

Before converting a file to a byte array (and vice versa), we assume that insrcThere is a folder namedtest.txtfile.

This istest.txtcontent

This is a
Test file.

Example1Convert File to byte[]

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
public class FileByte {
    public static void main(String[] args) {
        String path = System.getProperty("user.dir") + "\\src\\test.txt";
        try {
            byte[] encoded = Files.readAllBytes(Paths.get(path));
            System.out.println(Arrays.toString(encoded));
        } catch (IOException e) {
        }
    }
}

When running this program, the output is:

[84, 104, 105, 115, 32, 105, 115, 32, 97, 13, 10, 84, 101, 115, 116, 32, 102, 105, 108, 101, 46]

In the above program, we store the file path in the variable path.

Then, within the try block, we use the readAllBytes() method to read all bytes from the given path.

Then, we use the array's toString() method to print the byte array.

Since readAllBytes() may throw IOException, we use try in our program-catch block.

Example2Convert byte [] to File

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ByteFile {
    public static void main(String[] args) {
        String path = System.getProperty("user.dir") + "\\src\\test.txt";
        String finalPath = System.getProperty("user.dir") + "\\src\\final.txt";
        try {
            byte[] encoded = Files.readAllBytes(Paths.get(path));
            Files.write(Paths.get(finalPath), encoded);
        } catch (IOException e) {
        }
    }
}

When running the programtest.txtThe content will be copied tofinal.txt.

In the above program, we use the same method as the example1The same method reads all bytes from the File stored in path. These bytes are stored in the array encoded.

We also have a finalPath for writing bytes

Then, we use the Files.write() method to write the encoded byte array into the file at the given finalPath.

Comprehensive Java Examples