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

Tutoriel de base Java

Contrôle de flux Java

Java tableau

Java orienté objet (I)

Java orienté objet (II)

Java orienté objet (III)

Gestion des exceptions Java

Java Liste (List)

Java Queue (filet)

Java Map collectif

Java Set collectif

Java entrée/sortie (I/O)

Lecteur Java/Écrivain

Autres sujets Java

Un programme Java convertit des objets File (File) et des tableaux de bytes (byte[]) en Java

Java complete list of examples

Dans ce programme, vous apprendrez comment convertir un objet File en tableau de bytes en Java, et vice versa.

Avant de convertir un fichier en tableau de bytes (ou vice versa), nous supposons que danssrcDans le dossier, il y a un fichier nommétest.txtdu fichier.

C'esttest.txtdu contenu

Ceci est
Test file.

Exemple1Convertir un File en tableau de bytes

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) {
        }
    }
}

Lors de l'exécution de ce programme, la sortie est :

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

Dans le programme ci-dessus, nous stockons le chemin du fichier dans la variable path.

Ensuite, dans le bloc try, nous utilisons la méthode readAllBytes() pour lire tous les bytes du chemin donné.

Ensuite, nous utilisons la méthode toString() de l'array pour imprimer le tableau de bytes.

Comme readAllBytes() peut lever IOException, nous utilisons try dans notre programme-catch block.

Exemple2Convertir un tableau de bytes en 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 in 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 write() method of Files to write the encoded byte array into the file at the given finalPath.

Java complete list of examples