2020.8.3第二十八天
阿新 • • 發佈:2020-08-03
1.今天學習緩衝流
緩衝流的原理是將資料先緩衝起來,然後-起寫入或讀取出來,使用緩衝流讀寫檔案非常高效,常用的緩衝流有以下幾種: BufferedReader BufferedWriter. BufferedInputStream和BufferedOuputStream.1. 1.BufferedReader 與BufferedWriter
BufferedReader屬於字元流,如果要想使用BufferedReader就需要將一個字 節流變成字元流,為了解決這樣的問題,在Java中提供了以下兩個轉換類。
#將輸入的位元組流變為字元流: InputStreamReader.
#將輸出的字元流變為位元組流: OutputStreamWriter.
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) throwsIOException { 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章。