FileOutputStream(文件字节输出流)
- 文件字节输出流,负责写,该类用来创建一个文件并向文件中写数据(从内存到硬盘)
- 如果该流在打开文件进行输出前,目标文件不存在,那么该流会创建该文件
- FileOutputStream的write() 方法只接受byte[] 类型的参数,所以如果是String类型需要将String通过getBytes()方法转换为字节数组
- 写入数据的原理(内存—>硬盘)
Java程序–>JVM(Java虚拟机)–>OS(操作系统)–>OS调用写数据的方法–>把数据写入到文件中 - 字节输出流的使用步骤:
- 创建一个FileOutputStream对象,构造方法中传递写入数据的目的地
- 调用FileOutputStream对象中的方法write,把数据写入到文件中
- 释放资源(流使用会占用一定的内存,使用完毕后要把内存清空,提高程序的效率)
- 写出字节:write(int b) 方法,每次可以写出一个字节数据
- 写出字节数组:write(byte[] b),每次可以写出数组中的数据
- 写出指定长度字节数组:write(byte[] b, int off, int length) ,每次写出从off索引开始,length个字节
- 数据追加续写
public FileOutputStream(File file, boolean append): 创建文件输出流以写入由指定的 File对象表示的文件
public FileOutputStream(String name, boolean append): 创建文件输出流以指定的名称写入文件
boolean类型的值,append为true时,数据从文件尾部写入;append为false时,数据覆盖原文件
测试用例
- 在D:\Test文件下创建fosTest文件,向fosTest文件写
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStreamTest01 {
public static void main(String[] args) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("D:\\Test\\fosTest", true);
byte[] bytes = { 97, 98, 99, 100 };
fos.write(bytes);
fos.write(bytes, 0, 2);
String str = "五月天";
byte[] b = str.getBytes();
fos.write(b);
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}