FileOutputStream类
文件输出流是用于将数据写入 File 或 FileDescriptor 的输出流。(OutputSteam的子类)构造方法
public FileOutputStream(File file) throws FileNotFoundException创建一个向指定 File 对象表示的文件中写入数据的文件输出流。
public FileOutputStream(File file,boolean append)throws FileNotFoundException
创建一个向指定 File 对象表示的文件中写入数据的文件输出流。如果第二个参数为 true,则将字节写入文件末尾处,而不是写入文件开始处。创建一个新 FileDescriptor 对象来表示此文件连接。
append - 如果为 true,则将字节写入文件末尾处,而不是写入文件开始处
常用方法
public void write(int b) throws IOException:一次写一个字节
b- 要写入的字节。
public void write(byte[] b) throws IOException:
一次写一个字节数组
public void write(byte[] b, int off,int len) throws IOException:
一次写一部分字节数组
public void close()throws IOException
关闭此文件输出流并释放与此流有关的所有系统资源。此文件输出流不能再用于写入字节。
开发步骤:
1)创建字节输出流对象2)写数据
3)关闭资源
程序示例
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("fos.txt") ; //FileNotFoundException
// 使用流对象给文件中写入数据
fos.write("hello".getBytes());
//关闭资源
/**
* 1)将文件和流对象不建立关系了 (fos对象不指向fos.txt)
* 2)及时释放掉流对象所占用的内存空间
*/
fos.close();
/**
* 如果关闭流对象了,那么就不能对流对象进行操作了
*/
fos.write("java".getBytes());//java.io.IOException: Stream Closed :流已经关闭了
}
}