English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
En este programa, aprenderá cómo convertir un objeto File a byte [] en Java, y viceversa.
Antes de convertir el archivo a un array de bytes (o lo contrario), suponemos que ensrcEn la carpeta hay un archivo llamadotest.txtdel archivo.
Este estest.txtdel contenido
Esto es 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) { } } }
Al ejecutar este programa, la salida será:
[84, 104, 105, 115, 32, 105, 115, 32, 97, 13, 10, 84, 101, 115, 116, 32, 102, 105, 108, 101, 46]
En el programa anterior, almacenamos la ruta del archivo en la variable path.
Luego, dentro del bloque try, usamos el método readAllBytes() para leer todos los bytes del路径.
Luego, usamos el método toString() del array para imprimir el array de bytes.
Dado que readAllBytes() puede lanzar IOException, utilizamos try en nuestro programa-bloque catch.
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) { } } }
Al ejecutar el programa,test.txtEl contenido se copiará enfinal.txt.
En el programa anterior, utilizamos el mismo1El mismo método lee todos los bytes almacenados en el File almacenado en path. Estos bytes se almacenan en el array encoded.
Tenemos también un finalPath para escribir bytes
Luego, solo utilizamos el método write() de Files para escribir el array de bytes codificados en el archivo finalPath especificado.