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