Java FileOutputStream 类使用说明及实例
FileOutputStream 类用于以字节为单位将数据写入文件。在本教程中,我们将通过示例了解 Java FileOutputStream 类及其用法。
在本教程中,我们将通过示例了解 Java FileOutputStream 类及其用法。
java.io
包的 FileOutputStream
类用于以字节为单位将数据写入文件。
FileOutputStream
类扩展了 OutputStream
抽象类。
在了解之前 FileOutputStream
,请首先了解一下Java 文件操作。
创建一个文件输出流
FileOutputStream
类位于 java.io
包中,FileOutputStream
类提供了构造方法用来创建文件输出流。如下所示:
-
使用文件路径
// 通过 append 参数指定是否追加内容 FileOutputStream output = new FileOutputStream(String path, boolean append); FileOutputStream output = new FileOutputStream(String path);
参数说明:
path
: 文件的路径append
: 是否追加内容。如果为true
,则新数据追加到文件末尾,否则,新数据覆盖旧的数据。
-
使用文件的对象
File fileObject = new File(path);
FileOutputStream output = new FileOutputStream(File fileObject);
FileOutputStream 的方法
FileOutputStream
类实现了的 OutputStream
类中的定义的所有的抽象方法。
write() 方法
write()
- 将单个字节写到文件输出流write(byte[] array)
- 将指定字节数组中的字节写入输出流write(byte[] array, int start, int length)
- 将指定的字节数组中的指定长度的字节写入到输出流中
示例:FileOutputStream 将数据写入文件
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) {
String data = "This is a line of text inside the file.";
try {
FileOutputStream output = new FileOutputStream("output.txt");
byte[] array = data.getBytes();
// 写入字节
output.write(array);
output.close();
} catch(Exception e) {
e.getStackTrace();
}
}
}
在上面的例子中,我们创建了一个名为 output
的文件输出流,文件输出流连接了 output.txt
文件。
我们使用了 write()
方法将数据写入了文件。
当我们运行程序后, output.txt
文件中填充了以下内容:
This is a line of text inside the file.
! 注意:程序中使用 getBytes()
方法将字符串转换为字节数组。
flush() 方法
使用 flush()
方法刷新输出流。此方法强制输出流将所有数据写入目标。例如,
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileOutputStream out = null;
String data = "This is demo of flush method";
try {
out = new FileOutputStream(" flush.txt");
// 写数据
out.write(data.getBytes());
// 刷新输出流
out.flush();
out.close();
} catch(Exception e) {
e.getStackTrace();
}
}
}
当我们运行程序后, flush.txt
文件中填充了 data
字符串表示的文本。
close() 方法
close()
方法用来关闭文件输出流。一旦调用了 close()
方法,我们就不能使用输出流来写数据了。
FileOutputStream 的其他方法
方法 | 说明 |
---|---|
finalize() |
确保销毁对象的时候 close() 方法被调用 |
getChannel() |
返回与输出流相关联的 FileChannel 对象 |
getFD() |
返回与输出流关联的文件描述符 |