IO流部分记忆体系整理
这篇记录的是FileOutputStream、BufferedOutputStream
1.FileOutputStream【处理字节流。方向:内存向文件】
父类OutputStream
FileOutputStream类对象下面简写为out
(1)用指定输出流out,写回覆盖掉原来文件或者追加新内容到原来文件。
如果是追加,那么out已经完成了对原始文件所有内容的读取
(2)所有带缓冲区的输出流要执行flush操作,最后通过close关闭输出流
代码例子:
package com.cskaoyan.bytestream.out;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @description: 构造方法
* @author: 景天老师
**/
public class Demo1 {
public static void main(String[] args) throws IOException {
// 方式一:直接创建文件
//File file = new File("a1.txt");
//FileOutputStream out = new FileOutputStream(file);
// 方式二:用文件字节输出流
FileOutputStream fo = new FileOutputStream("D:\\test_root\\20210416\\dst\\a1.txt");
fo.write(System.lineSeparator().getBytes());
//FileOutputStream fo2 = new FileOutputStream(new File("a1.txt"));
//System.out.println(fo2);
//System.out.println(fo);
}
}
2.BufferedOutputStream【处理字节流。方向:内存向文件】
父类OutputStream
BufferedOutputStream类对象下面简写为bf
(1)用指定输出流bf,写回覆盖掉原来文件或者追加新内容到原来文件。
如果是追加,那么bf已经完成了对原始文件所有内容的读取
(2)所有带缓冲区的输出流要执行flush操作,最后通过close关闭输出流
代码例子:
package com.cskaoyan.bytestream.buff;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @description:
* @author: 景天老师
**/
/**
* 【1.】包装流:只需要close()
* 对于包装流,只需关闭最外层的流
*
*/
public class Demo {
public static void main(String[] args) throws IOException {
//FileOutputStream out = new FileOutputStream("a.txt");
//BufferedOutputStream bo = new BufferedOutputStream(out);
BufferedOutputStream bf = new BufferedOutputStream(new FileOutputStream(new File("a.txt")));
bf.write(97);
//bf.flush();
//是包装流
//只需关闭最外层的流
//close方法会执行flush方法
bf.close();
}
}