2.IO流
- input 输入
- output 输出
1.1字节输出流OutputStream
常用方法:
-
void write(int b);
向输出流指向的位置 , 输出一个字节.
-
void write(byte[] bytes);
向输出流指向的位置 , 输出一个字节数组 .
-
void write(byte[] bytes,int offset,int len);
向输出流指向的位置 , 输出一个字节数组的一部分 (从offset开始, 输出len个字节)
-
close()
关闭流, 释放占用的硬件资源.
public static void main(String[] args) {
OutputStream os = null;
try {
//输出流在输出数据时,如果文件不存在,则会创建文件并输出
os = new FileOutputStream(“D:\桌面\test\heihie.txt”);
//1.一次输出一个字节
os.write(54);
os.write(53);
//2.一次输出一组字节
byte[] bytes = “锄禾日当午,清明上河图”.getBytes();
os.write(bytes);
//3.一次输出一组字节,指定开始位置和整体长度
os.write(bytes,0,6);//通常字节流,不存在缓冲区,无需刷新管道 os.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { os.close(); } catch (IOException e) { e.printStackTrace(); } }
}
1.2文件字节输出流FileOutputStream
FileOutputStream 是 OuputStream 的实现类 , 是用于将字节 输出到文件中的 类.
文件输出流 输出时, 指向的文件可以不存在, 会创建文件并输出 .
构造方法:
- FileOutputStream(String filePath);
通过文件的绝对路径 , 创建一个指向文件的输出流.
- FileOutputStream(String filePath,boolean append);
参数1. filePath: 创建的流 , 指向的文件路径
参数2. append : 设置流是否为追加模式 .
(当值为false时, 会将之前的数据清空)
(当值为true时, 会接着之前的文件 继续存储)
- FileOutputStream(File file);
通过文件的file对象 , 创建一个指向文件的输出流.
- FileOutputStream(File file,boolean append);
参数1. file : 创建的流 , 指向的文件
参数2. append : 设置流是否为追加模式 .