English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在此程序中,您将学习如何在Java中将File对象转换为byte [],反之亦然。
在将文件转换为字节数组(反之亦然)之前,我们假设在src文件夹中有一个名为test.txt的文件。
这是test.txt的内容
This is a 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) { } } }
运行该程序时,输出为:
[84, 104, 105, 115, 32, 105, 115, 32, 97, 13, 10, 84, 101, 115, 116, 32, 102, 105, 108, 101, 46]
在以上程序中,我们将文件的路径存储在变量path中。
然后,在try块内,我们使用readAllBytes()方法从给定的路径中读取所有字节。
然后,我们使用数组的 toString()方法来打印字节数组。
由于readAllBytes()可能会引发IOException,因此我们在程序中使用了try-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) { } } }
Beim Ausführen des Programmstest.txtDer Inhalt wird infinal.txt.
Im obigen Programm verwenden wir denselben Ansatz wie im Beispiel1Der gleiche Ansatz liest alle Bytes aus dem im path gespeicherten File aus. Diese Bytes werden im Array encoded gespeichert.
Wir haben auch einen finalPath, um Bytes hineinzuschreiben
Dann verwenden wir nur die Methode write() von Files, um den codierten Byte-Array in die Datei am gegebenen finalPath einzuschreiben.