感谢大牛,学习自https://www.cnblogs.com/sxkgeek/p/9488703.html#_label1
BIO、NIO、NIO2学习日记
一、 预备知识
- 流概述
流是一组有有序的数据序列,根据具体操作类型,可以分为输入流和输出流。输入输出流作为目的地和源之间的通道将各种文件中的数据送到目的地(输入流)或将源中的数据送到各种文件(输出流)。 - 同步与异步
形容一次方法的调用,在单线程中。描述的是执行者是否具备主动通知功能和是否需要等待当前方法调用返回才执行后面的行为。
同步,调用者会等到方法调用返回后才能继续后面的行为
异步,调用者不需要等到方法返回,方法执行完毕后会主动通知调用者 - 阻塞与非阻塞
调用者是否可以执行多个任务,在多个线程中。描述的是调用者的多个线程是否可以同时执行
阻塞,线程1和线程2不能同时进行
非阻塞,线程1和线程2可以同时进行
总结了说,同步是让一个线程中的严格执行完当前方法才能进行下一个方法,阻塞是多个线程可同时进行
二、BIO
概述:作为传统的输入输出流,BIO是同步阻塞的,Java用于操作流的包都在java.io中。
- 分类
害,由于书上说的流还挺多的,不分类总觉得很乱。按照我的习惯,一般将流分为字符流(Reader/Writer)或者字节流(InputStream/OutStream),而其他分类还有按照输入输出流分为输入流(InputStream/Reader)或者输出流(OutStream/Writer)。在学习完这些流之后个人觉得其中缓存流字节流(BufferedInputStream/BufferedOutStream)和缓存字符流(BufferedReader/BufferedWriter)应该单独提出来,因为和其他输入和输出流的操作过程有一定区别。 - 字符流
下面是字符输出/输入流常用的方法
File file = new File("hello.txt");
try{
FileWriter out = new FileWriter(file);
String s = "helloworld";
out.writer(s); //可直接将字符串写入
out.close(); //不管什么流用完都需要关闭
}catch(Exception e){
e.printStackTrace();
}
try {
FileReader in = new FileReader(file);
int length = 0;
while(true){
char byt[] = new char[1024];
length = in.read(byt);
if(length == -1) break;
String str = new String(byt, 0, length);
System.out.println(str);
}
in.close();
} catch (Exception e) {
//TODO: handle exception
e.printStackTrace();
}
- 字节流
下面是字节输出/输入流常用的方法
try {
FileOutputStream out = new FileOutputStream(file);
byte buy[] = "hello".getBytes();
out.write(buy);
out.close();
} catch (Exception e) {
//TODO: handle exception
e.printStackTrace();
}
try {
FileInputStream in = new FileInputStream(file);
int length = 0;
while(true){
byte byi[] = new byte[1024];
length = in.read(byi);
if(length == -1) break;
String str = new String(byi, 0, length);
System.out.println(str);
}
in.close();
} catch (Exception e) {
//TODO: handle exception
e.printStackTrace();
}
- 缓存流
缓存字节流与普通字节流输出信息完全一样,不过构造缓存字节流的时候是和字节流不一样的,如下
BufferedInputStream(InputStream in); //in为我们要操作的普通字节流的对象
BufferedInputStream(InputStream in, int size); //也可以自定义缓存区大小size
BufferedOutputStream(OutputStream in); //需注意缓存输出流有flush()方法将缓存区内容强制输出
BufferedOutputStream(OutputStream in, int size);
缓存字符流常用方法
try {
FileWriter fw = new FileWriter(file);
BufferedWriter bufw = new BufferedWriter(fw);
String str[] = {"hello", "world"};
for(int i = 0; i < str.length; i++){
bufw.write(str[i]); //写入磁盘
bufw.newLine(); //定位下一行
}
bufw.flush(); //刷新
bufw.close();
fw.close();
} catch (Exception e) {
//TODO: handle exception
}
try {
FileReader fr = new FileReader(file);
BufferedReader bufr = new BufferedReader(fr);
String str = null;
while( (str = bufr.readLine()) != null ){ //逐行读取
System.out.println(str);
}
bufr.close();
fr.close();
} catch (Exception e) {
//TODO: handle exception
}
三、NIO(同步、非阻塞)
有点懒,以后再写~