如何使用 FileInputStream 从文件读取数据?

java 8object oriented programmingprogramming更新于 2025/9/19 22:04:17

FileInputStream 类从特定文件读取数据(逐字节)。它通常用于读取包含原始字节的文件内容,例如图像。

要使用此类读取文件内容 −

  • 首先,您需要通过传递一个字符串变量或一个 File 对象(表示要读取的文件路径)来实例化此类。
FileInputStream inputStream = new FileInputStream("file_path");
或者,
File file = new File("file_path");
FileInputStream inputStream = new FileInputStream(file);
  • 然后使用 read() 方法的任一变体 − 读取指定文件的内容
    • int read() − 该方法仅从当前 InputStream 读取数据,并逐字节返回读取的数据(以整数格式)。

      如果到达文件末尾,则此方法返回 -1。

    • int read(byte[] b) − 该方法接受一个字节数组作为参数,并将当前 InputStream 的内容读取到给定的数组中。

      此方法返回一个表示字节总数的整数,如果到达文件末尾,则返回 -1。

    • int read(byte[] b, int off, int len) −此方法接受一个字节数组、其偏移量 (int) 和长度 (int) 作为参数,并将当前 InputStream 的内容读取到给定数组中。
    • 此方法返回一个表示总字节数的整数,如果到达文件末尾,则返回 -1。

示例

假设我们在目录 D:/images

中有以下图像

以下程序使用 FileInputStream 读取上述图像的内容。

示例

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamExample {
   public static void main(String args[]) throws IOException {
      //创建 File 对象
      File file = new File("D:/images/javafx.jpg");
      //创建 FileInputStream 对象
      FileInputStream inputStream = new FileInputStream(file);
      //创建字节数组
      byte bytes[] = new byte[(int) file.length()];
      //将数据读入字节数组
      int numOfBytes = inputStream.read(bytes);
      System.out.println("Data copied successfully...");
   }
}

输出

Data copied successfully...

相关文章