import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileToByteExample {
// 使用 FileInputStream 将文件转换为 byte 数组
public static byte[] fileToByteUsingFileInputStream(File file) throws IOException {
try (FileInputStream fis = new FileInputStream(file)) {
byte[] byteArray = new byte[(int) file.length()];
fis.read(byteArray);
return byteArray;
}
}
// 使用 Files.readAllBytes 方法将文件转换为 byte 数组
public static byte[] fileToByteUsingFilesReadAllBytes(String filePath) throws IOException {
Path path = Paths.get(filePath);
return Files.readAllBytes(path);
}
public static void main(String[] args) {
File file = new File("example.txt");
try {
// 方法一:使用 FileInputStream
byte[] byteArray1 = fileToByteUsingFileInputStream(file);
System.out.println("File to byte array using FileInputStream: " + byteArray1);
// 方法二:使用 Files.readAllBytes
byte[] byteArray2 = fileToByteUsingFilesReadAllBytes(file.getAbsolutePath());
System.out.println("File to byte array using Files.readAllBytes: " + byteArray2);
} catch (IOException e) {
e.printStackTrace();
}
}
}
fileToByteUsingFileInputStream 方法:
FileInputStream
类读取文件内容并将其转换为字节数组。FileInputStream.read(byte[])
方法将文件内容读入到字节数组中。fileToByteUsingFilesReadAllBytes 方法:
Files.readAllBytes(Path path)
方法直接读取文件路径并将文件内容转换为字节数组。main 方法:
File
对象表示要读取的文件。IOException
异常。这两种方法都可以实现将文件转换为字节数组的功能,选择哪种方法取决于具体的应用场景和个人偏好。
上一篇:java求绝对值
下一篇:java 枚举定义
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站