java代码如何将一个文件中的内容读取并转换为字节数组呢?
下文笔者讲述文件读取为字节数组的方法及示例分享,如下所示
文件读取为字节数组的实现思路
借助io包中的FileInputStream对象
即可将文件内容读入
并转换为字节数组
例:文件读取为字节数组的示例
import java.io.*;
public class FileToByteArray {
public static void main(String[] args) {
FileInputStream fis = null;
byte[] byteArray = null;
try {
// 创建FileInputStream对象
fis = new FileInputStream("java265.txt");
// 创建字节数组
byteArray = new byte[fis.available()];
// 读取文件内容到字节数组中
fis.read(byteArray);
// 打印字节数组的内容
System.out.println("以下为字节数组中的内容:");
for (byte b : byteArray) {
System.out.print((char) b);
}
} catch (IOException e) {
System.out.println("Error reading file");
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
System.out.println("Error closing file input stream");
e.printStackTrace();
}
}
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


