2020.8.3第二十八天
1.今天学习缓冲流
缓冲流的原理是将数据先缓冲起来,然后-起写入或读取出来,使用缓冲流读写文件非常高效,常用的缓冲流有以下几种: BufferedReader BufferedWriter. BufferedInputStream和BufferedOuputStream.1. 1.BufferedReader 与BufferedWriter
BufferedReader属于字符流,如果要想使用BufferedReader就需要将一个字 节流变成字符流,为了解决这样的问题,在Java中提供了以下两个转换类。
#将输入的字节流变为字符流: InputStreamReader.
#将输出的字符流变为字节流: OutputStreamWriter.
在BufferedReader类中提供了一个专门的读取操作。
public String readLine() throws IOException
使用BufferedReader读取内容
1 import java.io.BufferedReader; 2 import java.io.FileInputStream; 3 import java.io. IOException; 4 import java.io. InputStreamReader; 5 public class BufferedReaderDemo{ 6 public static void main(String[] args) throws IOException { 7 read() ; 8 } 9 public static void read() throws IOException { 10 BufferedReader read = new BufferedReader (new InputStreamReader( 11 new FileInputStream ("D:/Hello.txt"))); 12 String line=null; 13 while ((line=read.readLine())!=null) { 14 System.out.println(line) ; 15 } 16 read.close() ; 17 } 18 }
使用BufferedWriter读取内容
1 import java.io.BufferedWriter; 2 import java.io.FileOutputStream; 3 import java.io.IOException; 4 import java.io.OutputStreamWriter; 5 public class BufferedWriterDemo { 6 public static void main(String[] args) throws IOException { 7 write () ; 8 } 9 public static void write() throws IOException{ 10 BufferedWriter w=new BufferedWriter (new OutputStreamWriter ( 11 new FileOutputStream ("D:/Hello.txt"))); 12 w.write("Hello"); 13 w.write ("Java") ; 14 w.close() ; 15 } 16 }
2.BufferedinputStream与BufferedoutputStream
读取或写入影像数据
1 import java.io.BufferedInputStream; 2 import java.io.BufferedOutputStream; 3 import java.io.FileInputStream; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 public class BufferedInputOutput { 7 public static void main(String[] args) throws IOException{ 8 outIn(); 9 } 10 public static void outIn() throws IOException { 11 BufferedInputStream in = new BufferedInputStream (new FileInputStream( 12 "D:\\test.png")); 13 BufferedOutputStream out = new BufferedOutputStream ( 14 new FileOutputStream("D:\\test2.png")); 15 byte[] buf=new byte [1024]; 16 int len = -1; 17 while ((len=in.read (buf))!=-1) { 18 out.write (buf,0, len); 19 } 20 out.close(); 21 in.close(); 22 } 23 }
2.遇到的问题:没有弄清楚各种流的关系。
3.明天继续学习第12章。