21xrx.com
2025-03-21 06:57:06 Friday
文章检索 我的文章 写文章
如何在Java中实现将文件写入数组
2023-06-12 03:40:55 深夜i     --     --
Java 文件写入数组 FileInputStream ByteArrayOutputStream Files readAllBytes

在Java编程中,经常需要读取和写入文件。当需要将文件中的数据存储到数组中时,该如何实现呢?本文将介绍如何在Java中将文件写入数组,并给出示例代码。

1. 使用FileInputStream和ByteArrayOutputStream

File file = new File("filename.txt");
byte[] buffer = new byte[(int) file.length()];
InputStream inputStream = null;
try {
  inputStream = new FileInputStream(file);
  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  int read;
  while ((read = inputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, read);
  }
  buffer = outputStream.toByteArray();
} catch (IOException e) {
  e.printStackTrace();
} finally {
  if (inputStream != null) {
    try {
      inputStream.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

2. 使用Files和readAllBytes

Path path = Paths.get("filename.txt");
byte[] buffer = new byte[0];
try {
  buffer = Files.readAllBytes(path);
} catch (IOException e) {
  e.printStackTrace();
}

以上两种方法都可以实现将文件写入数组。第一种方法使用了FileInputStream和ByteArrayOutputStream,逐个字节读取文件并写入到字节数组中,最终将写入完成的字节数组输出。第二种方法使用了Files类的readAllBytes方法,直接将整个文件读取到字节数组中。

  
  

评论区

    相似文章