2019-02-25 10:57:35 卢浮宫 版权声明:本文为站长原创文章,转载请写明出处
一、流就像水流,是承载字节和字符的数据。
二、输入流:数据从文件流向内存。 输入流:数据从内存流向文件
三、java中字节流是处理的是单个字节,通常处理二进制数据。字符流是unicode码,通常用于处理文本数据。
四、在字节流中的输入用InputStream、输出用OutputStream。字符流读取用Read,写入用Write。
需要注意的是InputStream、OutputStream、Read、Write都是抽象类,不能使用new
五、相互转换
字符转字节时:String str = "xa"; byte[] bt = str.getBytes();
byte[] b={(byte)0xB8,(byte)0xDF,(byte)0xCB,(byte)0xD9}; String str= new String (b);
六、示例如下:
①字节流读取文件内容 (输出文件内容 : this is a test data. 你好)
private static void inputStreamRead() throws IOException{
FileInputStream fis = new FileInputStream("D:\xa.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] bt = new byte[1024];
int len;
while ((len = bis.read(bt))!= -1) {
System.out.println(new String(bt,0,len));
}
bis.close();
fis.close();
}
②字节流写入文件内容(hello world .你好)
private static void outputStreamWrite() throws IOException{
FileOutputStream fos = new FileOutputStream("D:\x.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write("hello world.你好".getBytes());
bos.close();
fos.close();
}
③字符流读取文本(输出同①)
private static void fileReadRead() throws IOException{
FileReader fir = new FileReader("D:\xa.txt");
BufferedReader bfr = new BufferedReader(fir);
String line;
while ((line = bfr.readLine()) != null) {
System.out.println(line);
}
bfr.close();
fir.close();
}
④字符流写入文件
private static void fileWriteWrite() throws Exception{
FileWriter fiw = new FileWriter("D:\x.txt");
BufferedWriter bfw = new BufferedWriter(fiw);
bfw.write("this is a test data. 你好啊");
bfw.close();
fiw.close();
}
七、5中IO模型
1、首先了解以下概念
同步:调用功能时按顺序执行,不可逾越。
异步:调用功能,可能不止到返回结果,当有结果返回时通知我(一般是用回调函数)。
阻塞:当你在调用我的功能时,没有结果时我不会返回数据。
非阻塞:调用我时,立即返回结果。
2、模型如下
①阻塞IO:一个IO函数被调用时会等待执行,数据没有准备好时进入等待,准备好了就进行数据拷贝。
②非阻塞IO:通过反复调用IO函数来执行。但是在数据拷贝时线程是阻塞的。
③异步IO:在调用IO函数时,调用者不能马上得到结果,等待有结果时再通知你进行处理。
④IO复用:对IO函数进行两次调用,两次返回(没有什么优越性)。
⑤信号驱动IO:安装信号处理函数,数据准备好时就在信号处理函数中处理数据。