Java 程序:将文件转换为字节数组及其逆转换
要理解此示例,你应该具备以下 Java 编程主题的知识:
在我们将文件转换为字节数组及反向转换之前,我们假设在我们的 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) {
}
}
}
输出
[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
的文件中。