Java FileInputStream 读取文件并写入内容:完整指南及代码示例

本文将详细介绍如何在 Java 中使用 FileInputStream 读取文件并使用 FileOutputStream 写入文件,并提供完整的代码示例。本指南涵盖了文件读取、写入、错误处理和资源关闭等方面,帮助你轻松完成文件操作。

步骤

  1. 创建 FileInputStream 对象来读取源文件。可以使用文件路径或者 File 对象作为构造函数的参数。
  2. FileInputStream fis = new FileInputStream("path/to/source/file");
  3. 创建 FileOutputStream 对象来写入目标文件。同样可以使用文件路径或者 File 对象作为构造函数的参数。
  4. FileOutputStream fos = new FileOutputStream("path/to/destination/file");
  5. 创建一个 byte 数组来存储读取的数据。可以根据需要设置数组的大小。
  6. byte[] buffer = new byte[1024];
  7. 使用 FileInputStream 的 read() 方法读取数据,并将读取的数据存储到 byte 数组中。read() 方法返回 -1 表示文件已经读取完毕。
  8. int bytesRead;while ((bytesRead = fis.read(buffer)) != -1) {   // 写入目标文件   fos.write(buffer, 0, bytesRead);}
  9. 在完成文件读取和写入后,关闭 FileInputStream 和 FileOutputStream 对象。
  10. fis.close();fos.close();

完整代码示例

import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;public class FileCopyExample {   public static void main(String[] args) {     FileInputStream fis = null;    FileOutputStream fos = null;    try {       fis = new FileInputStream("path/to/source/file");       fos = new FileOutputStream("path/to/destination/file");      byte[] buffer = new byte[1024];      int bytesRead;      while ((bytesRead = fis.read(buffer)) != -1) {         fos.write(buffer, 0, bytesRead);      }    } catch (IOException e) {       e.printStackTrace();    } finally {       try {         if (fis != null) {           fis.close();        }        if (fos != null) {           fos.close();        }      } catch (IOException e) {         e.printStackTrace();      }    }  }}

注意:以上代码只是一种简单的示例,如果需要处理更复杂的文件操作,例如处理大文件或者需要确保文件关闭等情况,可能需要添加更多的错误处理和异常处理。


原文地址: https://www.cveoy.top/t/topic/p4Oo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录