1、介绍
FileOutputStream是字节输出流的一种,继承于OutputStream,主要是用于写入诸如图像数据的原始字节流,其类图如图所示。
2、构造方法
构造方法 | 主要作用 |
FileOutputStream(File file) | 创建文件输出流以写入由指定的 |
FileOutputStream(File file, boolean append) | 创建文件输出流以写入由指定的 |
FileOutputStream(FileDescriptor fdObj) | 创建文件输出流以写入指定的文件描述符,表示与文件系统中实际文件的现有连接 |
FileOutputStream(String name) | 创建文件输出流以指定的名称写入文件 |
FileOutputStream(String name, boolean append) | 创建文件输出流以指定的名称写入文件;boolean 如果为true ,那么字节将被写入文件的末尾,而不是开头 |
3、常见方法
方法 | 作用 |
write(byte[] b) | 将 |
write(byte[] b, int off, int len) | 从位于偏移量 |
write(int b) | 将指定的字节写入此文件输出流 |
close() | 关闭此文件输出流并释放与此流相关联的任何系统资源。此文件输出流可能不再用于写入字节。如果该流具有相关联的信道,则该信道也被关闭。 |
4、示例
需求:在a.txt文件中写入"hello,world!"
分析:
1、先创建fileOutputStream对象。
2、将内容写入到文件中。
3、关闭文件流,释放资源。
package com.IO.OutputStream;
import java.io.*;
public class FileOutputStreamDemo {
public static void main(String[] args) {
file_output_stream();
}
public static void file_output_stream() {
String pathname = "D:\\file\\a.txt";
//1、创建FileOutputStream对象
FileOutputStream fileOutputStream = null;
try {
// fileOutputStream = new FileOutputStream(pathname); //这是将原本文件内容覆盖后重新写入,即从文件开头写起
fileOutputStream = new FileOutputStream(pathname, true);//这是从文件中的最后位置写入,即追加到文件末尾
//2、将内容写入文件中
// fileOutputStream.write('H'); //这是写入单个字节的写法
String data = "hello,world!";
//getBytes():使用平台的默认字符集将该字符串编码为一个字节序列,并将结果存储到一个新的字节数组中。
// 当此字符串无法在默认字符集内编码时,此方法的行为是未指定的。当需要对编码过程进行更多的控制时,
// 应该使用CharsetEncoder类。
fileOutputStream.write(data.getBytes());//这是写入多个字节的写法
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}