在将文件转换为字节数组(反之亦然)之前,我们假设我们的 src 文件夹中有一个名为 test.txt 的文件。
这是test.txt的内容
this is a
Test file.
示例1: 将文件转换为字节[]
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) { } } }
v
[84, 104, 105, 115, 32, 105, 115, 32, 97, 13, 10, 84, 101, 115, 116, 32, 102, 105, 108, 101, 46]
在上面的程序中,我们将文件的路径存储在变量
path中。
然后,在 try 块中,我们使用
readAllBytes()
方法从给定路径读取所有字节。
然后,我们使用
Arrays
'
toString()
方法打印字节数组。
由于
readAllBytes()
可能会抛出
IOException
,我们在程序中使用了
try-catch
块。
示例 2: 将 byte[] 转换为 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) { } } }
当您运行程序时,test.txt 的内容被复制到 final.txt。
在上面的程序中,我们使用与示例 1 相同的方法从存储在
path 中的 File 中读取所有字节。这些字节存储在
encoded 数组中。
我们还有一个
finalPath 用于写入字节。
然后,我们只需使用
Files
'
write()
方法将编码的字节数组写入给定
finalPath 中的 File。