流
概念:内存与存储设备之间数据的交换,数据需要依靠流进行传输
流可具体分为三类:
按方向分:
- 输入流:将存储设备中的数据读进内存中
- 输出流:将内存中的数据写到存储设备中
按单位分:
- 字节流:以字节为数据的传输单位,可读写任何数据
- 字符流:以字符为数据的传输单位,只能读写文本数据
按功能分:
- 节点流:具有实际传输数据的读写功能
- 过滤流:在节点流之上增强功能
字节流
字节流的父类:
InputStream(字节输入流):
- public int read();
- public int read(byte[] a);
- public int read(byte[] a,int index,int len);
OutputStream(字节输出流):
- public void write(int a);
- public void write(byte[] a);
- public void write(byte[] a,int index,int len);
字节节点流:
文件流:
FileInputStream:构造时可传入文件的相对路径或绝对路径,也可以传入文件对象
FileOutputStream:构造时可传入文件的相对路径或绝对路径,也可以传入文件对象,构造时可选择是否覆盖原文件,默认false覆盖,ture不覆盖
字节过滤流:
缓冲流:
BufferedInputStream:构造时传入一个字节输入节点流
BufferedOutputStream:构造时传入一个字节输出节点流
- 可提高IO效率,减少磁盘访问次数
- 访问的数据存储在缓冲区中,flush()可将缓冲区数据写出并刷新缓冲区,close方法也会默认调用flush()
对象流:
ObjectInputStream:构造时传入一个字节输入节点流
ObjectOutputStream:构造时传入一个字节输出节点流
- 增强了缓冲区的功能
- 增加了读写基本数据类型和字符串的功能
- 增加了读写对象的功能
readObject() //从流中读取一个对象(反序列化)
writeObject() //从流中输出一个对象(序列化)
其中读写对象时,需注意以下内容呢:
- 对象必须实现serializable接口
- 必须保证对象的所有属性均为可序列化
- transient修饰的属性为临时属性,可以不参与序列化
- 读取时如果读取到对象尾部,则会抛出java.io.EOFException异常
PrintWriter:
- 构造时传入一个字节输出节点流
- 封装了print/println方法,可实现写入后换行
以下为一个简单的综合案例
public static void main(String[] args) {
OutputStream os = null;
PrintStream ps = null;
InputStream is = null;
BufferedInputStream bi = null;
try {
os = new FileOutputStream("test.txt");
ps = new PrintStream(os);
is = new FileInputStream("test.txt");
bi = new BufferedInputStream(is);
ps.println("Hello");
ps.print("World");
ps.flush();
byte[] b = new byte[4];
while (true){
int count = bi.read(b);
for (int i = 0;i<count;i++){
System.out.print((char)b[i]);
}
if (count < b.length) break;
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (ps != null) ps.close();
if (bi != null) bi.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
字符流
字节流的父类:
Reader(字符输入流):
- public int read();
- public int read(char[] a);
- public int read(char[] a,int index,int len);
Writer(字符输出流):
- public void write(int a);
- public void write(char[] a);
- public void write(char[] a,int index,int len);
- public void write(String str);
字符节点流:
文件流:
FileReader:构造时可传入文件的相对路径或绝对路径,也可以传入文件对象
FileWriter:构造时可传入文件的相对路径或绝对路径,也可以传入文件对象,构造时可选择是否覆盖原文件,默认false覆盖,ture不覆盖
以上节点流自带缓冲区
字符过滤流:
缓冲流:
BufferedReader:构造时传入一个字符输入节点流
BufferedWriter:构造时传入一个字符输出节点流
- 支持输出换行符
- 支持读一行,写一行
PrintWriter:
- 构造时传入一个字符输出节点流
- 封装了print/println方法,可实现写入后换行
以下为一个简单的综合案例:
public static void main(String[] args) {
Writer w = null;
PrintWriter pw = null;
Reader r = null;
BufferedReader br = null;
try {
w = new FileWriter("test.txt");
pw = new PrintWriter(w);
r = new FileReader("test.txt");
br = new BufferedReader(r);
pw.println("你好");
pw.print("世界");
pw.flush();
while (true){
String str = br.readLine();
if (str == null) break;
System.out.println(str);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (pw != null) pw.close();
if (br != null) br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
本文章仅供个人参考学习,欢迎各位大佬交流与改正