从文件中读取字节数组的 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[] 转换为 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
中读取所有字节。 这些字节存储在数组中.
我们还有一个 finalPath
存储要写入文件的位置。
然后,我们简单地使用 Files.write()
方法将字节数组 encoded
写入 finalPath
给定的文件中。