OutputStream 字节输出基类
写操作步骤
步骤1:打开字节输出流,可能会抛出FileNotFoundException异常
String path = “/Users/gongdezhe/Desktop/test.txt”;
FileOutputStream outputStream = new FileOutputStream(path);
写操作时,文件不存在,会自动创建文件,并写入数据
当文件目录路径不合法是则会抛出异常
步骤2:写操作,可能会抛出IOException异常
void write(int b) 每次写入一个字节
步骤3:关闭流,可能会抛出IOException异常
outputStream.close();
方法介绍:
void write(int b) :
每次写入一个字节
void write(byte b[]) ;
批量写入,写入类型为byte[]
void write(byte b[], int off, int len)
批量写入,可以自定义从byte数组的起始和读取长度
void flush()
刷新缓存
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public static void Write() {
//写操作介绍
//步骤1:打开字节输出流,可能会抛出FileNotFoundException异常
String path = "C:\\Users\\lenovo\\Desktop\\a.txt";
//写操作时,文件不存在,会自动创建文件,并写入数据
//当文件目录路径不合法时则会抛出异常
try{
FileOutputStream outputStream = new FileOutputStream(path);
//步骤2:写操作,可能会抛出IOException异常
//void write(int b); 每次写入一个
// outputStream.write(99);
// void write(byte b[]) 批量写入,写入类型为byte[]
byte[] bytes = {'a','b','c'};
// outputStream.write(bytes);//abc写入
// outputStream.write("hello".getBytes());
//void write(byte[] b,int off,int len); //批量写入,可以自定义从byte数组的起始和读取长度
outputStream.write(bytes,0,2); //[1,2) 必须在byte[]数组的长度的有效范围内
outputStream.getFD(); //通道相关
outputStream.getChannel();//文件
outputStream.flush(); //提醒磁盘直接发送文件,刷新缓存,刷新内核区
//步骤3:关闭流,可能会抛出IOException异常
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}