Java I/O---Reader & Writer(字元流)

來源:互聯網
上載者:User

標籤:dwr   子類   abc   階層   amt   java編程   back   sep   inline   

1.Reader & Writer

       當我們初次看見Reader和Writer類時,可能會以為這是兩個用來替代InputStream和OutputStreamt的類,但實際上並非如此。

       儘管一些原始的“流”類庫不再被使用(如果使用它們,則會收到編譯器的警告資訊),但是InputStream和OutputStreamt在以   面向位元組形式的I/O中仍可以提供極有價值的功能,Reader和Writer提供相容Unicode與面向字元的I/O功能。

       有時我們必須把來自於 “位元組” 階層中的類和 “字元 ” 階層中的類結合起來使用(實現位元組和字元的轉化)。 為了實現這個目的,要用到 “適配器” ( adapter )類: lnputStreamReader(子類FileReader)可以把 InputStream轉換為Reader(位元組轉化為字元),而         OutputStreamWriter(子類FileWriter)可以把OutputStream轉換Writer(字元轉化為位元組)。

       Java I/O---字元與位元組轉換流---FileReader&FileWriter

2. BufferedReader & BufferedWriter

      兩個類實現字元流緩衝

 

  1 public class CharStreamBufferDemo {  2   3 /**  4  * @param args  5  * @throws IOException  6  */  7 public static void main(String[] args) throws IOException {  8   9 /* 10  * 示範字元流的緩衝區。 11  * BufferedReader 12  * BufferedWriter 13  */ 14 //writeTextByBuffered(); 15 readTextBuffered(); 16  17 //讀取鍵盤錄入專業。Scanner=流+Regex。方法都是按照某種規則在讀取資料。 18 //BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)) 19 //bufr.readLine(); 20 } 21  22 public static void readTextBuffered() throws IOException { 23  24 FileReader fr = new FileReader("tempfile\\bufw.txt");//將位元組轉化為字元 25  26 BufferedReader bufr = new BufferedReader(fr); 27  28 String line = null; 29 while((line=bufr.readLine())!=null){ 30  31 System.out.println(line); 32  33 } 34  35 /*String line1 = bufr.readLine(); 36 System.out.println(line1); 37 String line2 = bufr.readLine(); 38 System.out.println(line2); 39 String line3 = bufr.readLine(); 40 System.out.println(line3); 41 String line4 = bufr.readLine(); 42 System.out.println(line4); 43 String line5 = bufr.readLine(); 44 System.out.println(line5);*/ 45  46 bufr.close(); 47  48 } 49  50 public static void writeTextByBuffered() throws IOException { 51  52 //1,明確目的。 53 FileWriter fw = new FileWriter("tempfile\\bufw.txt");//將字元轉為位元組 54  55 //2,建立緩衝區對象。明確要緩衝的流對象。 56 BufferedWriter bufw = new BufferedWriter(fw); 57  58 for(int x=1; x<=4; x++){ 59  60 bufw.write(x+"abc"); 61 bufw.newLine(); 62 bufw.flush(); 63 } 64  65 //bufw.write("abc"); 66 //bufw.newLine();//System.getProperty("line.separator"); 67 //bufw.write("hello"); 68 bufw.close(); 69  70 } 71  72 } 73 

2017-12-31

內容來自java編程思想的傳智播客課程

Java I/O---Reader & Writer(字元流)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.