在我们将文件转换为字节数组以及反之亦然之前,我们假设在我们的 src 文件夹中有一个名为 test.txt 的文件。
这是 test.txt 的内容
This is a Test file.
示例 1:将文件转换为 byte[]
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[] 转换为文件
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 中的文件读取所有字节。这些字节存储在数组 encoded 中。
我们还有一个 finalPath,字节将被写入其中。
然后,我们只需使用 Files
的 write()
方法将编码的字节数组写入给定 finalPath 的文件中。