Java输入输出流:FileInputStream、FileOutputStream与缓冲流操作 第二篇

目录

一、FileInputStream与FileOutputStream详解

FileInputStream类

核心方法解析

示例代码:读取文件内容

FileOutputStream类

核心方法解析

示例代码:向文件写入数据


一、FileInputStream与FileOutputStream详解

FileInputStream类

类定义与构造方法 java.io.FileInputStream是Java中用于从文件读取字节的字节输入流类。其定义如下:

public class FileInputStream extends InputStream

FileInputStream继承自InputStream,提供了从文件中读取原始字节数据的功能。主要构造方法如下:

FileInputStream(File file)
FileInputStream(String name)
  • FileInputStream(File file):通过java.io.File对象指定要读取的文件。
  • FileInputStream(String name):通过文件路径字符串指定要读取的文件。

这两个构造方法均会尝试打开指定的文件以供读取,如果文件不存在或者由于权限问题无法打开,将抛出FileNotFoundException

核心方法解析

  1. read()

    • 方法签名:int read()int read(byte[] b)int read(byte[] b, int off, int len)
    • 用途:从文件中读取字节数据。
    • 返回值:成功读取到的字节数(非负整数),若已到达文件末尾或发生I/O错误,则返回-1。
    • 注意事项:
      • 单字节读取:read()方法每次仅读取一个字节,效率较低,通常用于读取未知长度的二进制数据。
      • 批量读取:read(byte[] b)read(byte[] b, int off, int len)方法允许一次读取多个字节到数组中,后者还可以指定数组内的偏移量和读取长度。应优先使用批量读取以提高效率。
      • 返回值判断:当返回值为-1时,表示已到达文件末尾或发生错误,此时应停止读取并进行相应处理。
  2. available()

    • 方法签名:int available()
    • 用途:返回当前可无阻塞地从此输入流读取(或跳过)的估计字节数。
    • 返回值:估计可用的字节数;若返回0,则不保证下一次read操作不会阻塞。
    • 注意事项:
      • 只是估计值:available方法返回的是一个估计值,实际可读取的字节数可能小于该值,甚至在两次调用之间发生变化。因此,不应依赖available方法来确定文件的总长度或剩余长度。
      • 用于优化读取:在某些情况下,可用作优化策略,例如在网络I/O中预先分配缓冲区大小。
  3. close()

    • 方法签名:void close()
    • 用途:关闭此FileInputStream并释放与此流关联的所有系统资源。
    • 注意事项:
      • 必须调用:在完成文件读取后,务必调用close方法关闭流,否则可能导致资源泄漏和数据丢失。
      • 异常处理:close方法可能会抛出IOException,需要妥善处理。

示例代码:读取文件内容

import java.io.*;

public class FileInputStreamExample {
    public static void main(String[] args) {
        String filePath = "path/to/file.txt";
        byte[] buffer = new byte[1024]; // 创建缓冲区

        try (FileInputStream fis = new FileInputStream(filePath)) {
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) { // 批量读取
                // 处理读取到的字节数据,如打印、解析等
                System.out.write(buffer, 0, bytesRead);
            }
        } catch (FileNotFoundException e) {
            System.err.println("File not found: " + filePath);
        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }
    }
}

上述代码展示了如何使用FileInputStream读取文件内容。首先创建FileInputStream对象并指定要读取的文件路径。然后,使用一个循环不断调用read方法批量读取文件内容,并在循环体内处理读取到的字节数据。最后,使用try-with-resources语句确保FileInputStream在读取完成后被正确关闭。

FileOutputStream类

类定义与构造方法 java.io.FileOutputStream是Java中用于向文件写出字节数据的字节输出流类。其定义如下:

public class FileOutputStream extends OutputStream

FileOutputStream继承自OutputStream,提供了将字节数据写入文件的功能。主要构造方法如下:

FileOutputStream(File file)
FileOutputStream(String name)
FileOutputStream(File file, boolean append)
FileOutputStream(String name, boolean append)
  • FileOutputStream(File file)FileOutputStream(String name):创建一个FileOutputStream,如果指定的文件不存在,将创建新文件;如果文件已存在,原有内容将被覆盖。
  • FileOutputStream(File file, boolean append)FileOutputStream(String name, boolean append):当append参数为true时,写入的数据将追加到文件的末尾,而非覆盖原有内容。

核心方法解析

  1. write()

    • 方法签名:void write(int b)void write(byte[] b)void write(byte[] b, int off, int len)
    • 用途:将指定的字节数据写入到文件中。
    • 返回值:无返回值。
    • 注意事项:
      • 单字节写入:write(int b)方法每次写入一个字节,效率较低,通常用于写入未知长度的二进制数据。
      • 批量写入:write(byte[] b)write(byte[] b, int off, int len)方法允许一次写入多个字节,后者还可以指定数组内的偏移量和写入长度。应优先使用批量写入以提高效率。
      • 数据同步:写入操作可能不会立即反映到磁盘上,需要调用flush方法确保数据被完全写入。
  2. flush()

    • 方法签名:void flush()
    • 用途:强制将所有缓冲的输出字节刷新到目标文件。
    • 返回值:无返回值。
    • 注意事项:
      • 数据一致性:在写入重要数据后或程序结束前,应调用flush方法确保数据被完全写入,防止因程序异常终止导致数据丢失。
  3. close()

    • 方法签名:void close()
    • 用途:关闭此FileOutputStream并释放与此流关联的所有系统资源。
    • 注意事项:
      • 必须调用:在完成文件写入后,务必调用close方法关闭流,否则可能导致资源泄漏和数据丢失。
      • 自动flush:close方法会隐式调用flush方法,确保所有数据被写入文件。
      • 异常处理:close方法可能会抛出IOException,需要妥善处理。

示例代码:向文件写入数据

import java.io.*;

public class FileOutputStreamExample {
    public static void main(String[] args) {
        String filePath = "path/to/output.txt";
        byte[] dataToWrite = "Hello, World!".getBytes(); // 要写入的字节数据

        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            fos.write(dataToWrite); // 批量写入
            fos.flush(); // 确保数据被写入
        } catch (FileNotFoundException e) {
            System.err.println("File not found: " + filePath);
        } catch (IOException e) {
            System.err.println("Error writing to file: " + e.getMessage());
        }
    }
}

上述代码展示了如何使用FileOutputStream向文件写入数据。首先创建FileOutputStream对象并指定要写入的文件路径。然后,使用write方法将字节数据写入文件,并调用flush方法确保数据被完全写入。最后,使用try-with-resources语句确保FileOutputStream在写入完成后被正确关闭。

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值