目录
一、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
。
核心方法解析
-
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时,表示已到达文件末尾或发生错误,此时应停止读取并进行相应处理。
- 单字节读取:
- 方法签名:
-
available():
- 方法签名:
int available()
- 用途:返回当前可无阻塞地从此输入流读取(或跳过)的估计字节数。
- 返回值:估计可用的字节数;若返回0,则不保证下一次read操作不会阻塞。
- 注意事项:
- 只是估计值:available方法返回的是一个估计值,实际可读取的字节数可能小于该值,甚至在两次调用之间发生变化。因此,不应依赖available方法来确定文件的总长度或剩余长度。
- 用于优化读取:在某些情况下,可用作优化策略,例如在网络I/O中预先分配缓冲区大小。
- 方法签名:
-
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时,写入的数据将追加到文件的末尾,而非覆盖原有内容。
核心方法解析
-
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方法确保数据被完全写入。
- 单字节写入:
- 方法签名:
-
flush():
- 方法签名:
void flush()
- 用途:强制将所有缓冲的输出字节刷新到目标文件。
- 返回值:无返回值。
- 注意事项:
- 数据一致性:在写入重要数据后或程序结束前,应调用flush方法确保数据被完全写入,防止因程序异常终止导致数据丢失。
- 方法签名:
-
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在写入完成后被正确关闭。