1.文件字节流
(1).文件字节输出流用法
构造方法:
FileOutputStream(String path); //路径代表写出到哪个文件中
File OutputStream(File file);
FileOutputStream(String path,boolean append);//append: true: 如果源文件有内容,在内容后追加
File OutputStream(File file,boolean append);
成员方法:
write(int a);
write(byte[] bs);
write(byte[]bs,int offset,int len);
2 文件字节输入流用法
构造方法:
FileInputStream(String path);//代表从哪个文件中读取数据
FileInputStream(File file);
成员方法:
public int read() 每次读取一个字节,并返回
public int read(byte[] b) 每次读取一个数组长度的字节,数组存到了数组中,返回真正读取回来的长度
3 拷贝文件
使用字节流可以拷贝任意文件
流程: 从一个文件中一个一个的读取数组,然后在一个一个的写到文件中
4.缓冲字节输出流
BufferedOutputStream(OutputStream);
flush: 缓冲输出流中特有的方法,将缓冲区中的内容写到文件中
close: 会先调用flush方法,在关流
5.缓冲字节输入流
BufferedInputStream(InputStream)
BufferedInputStream(InputStream,int size) size: 缓冲区大小,默认8k
6.转换流(字符流)
字符流:字节流+编码
编码: 把文字转成二进制 encode
解码: 把二进制转成文件 decode
字符流只能处理纯文本文件(用记事本 打开能看懂)
场景:
可以指定编码
也可以把字节流转成字符流
7.字符输出流
构造方法:
public OutputStreamWriter(OutputStream out)
public OutputStreamWriter(OutputStream out,String charsetName)
成员方法:
public void write(int c)
public void write(char[] cbuf)
public void write(char[] cbuf,int off,int len)
public void write(String str)
public void write(String str,int off,int len)
8.字符输入流
构造方法
public InputStreamReader(InputStream in)
public InputStreamReader(InputStream in,String charsetName)
成员方法:
public int read()
public int read(char[] cbuf)
9.拷贝文件
只能拷贝纯文本文件
10.简化流(字符流)
不能指定编码,也不能把字节流转成字符流
FileReader/FileWriter
一个程序中先写后读的注意事项:
如果在一个程序中,向同一个文件中写数据,并读回来:
写完数据后,要关流,否则会导致输出流继续占用文件,这样输入流就无法读出数据
11 .缓冲字符流读和写
BufferedWriter**
void newLine()
BufferedReader**
String readLine()
12.序列化和对象流
序列化: 把对象转成二进制
反序列化: 把二进制转成对象
持久化: 把内存数据存储到磁盘上(一般数据库)
实现序列化步骤:
(1).让类实现Serializable接口
(2).使用ObjectOutputStream 写数据:调用writeObject
(3).使用ObjectInputStream 读数据:调用readObject