IO字符流緩衝區知識點分解與講解

注意:(1)readLine()和newLine()方法的使用。

           (2)使用緩衝區注意要刷新即:xxx.flush()

字符流緩衝區:
緩衝區出現提高流的的讀寫效率。

所以在創建緩衝區之前,必須要先有流對象。

對應類:
BufferedWriter。
BufferedReader。
緩衝區要結合流纔可以使用。

該緩衝區中提供了一個跨平臺的換行符:newLine()方法
*/
import java.io.*;
class BufferedWriterDemo
{
 public static void main(String[] args) throws IOException
 {
  //創建一個字符寫入流對象。
  FileWriter fw =new FileWriter("buf.txt");
  
  //爲了提高字符寫入流效率,加入了緩衝技術。
  //只要將需要被提高效率的流對象作爲參數傳遞給緩衝區的構造即可。
  BufferedWriter bufw = new BufferedWriter(fw);

  for(int x=1; x<5; x++)
  {
   bufw.write("abcde"+x);
   bufw.newLine();
   bufw.flush();
  }
  //記住,只要用到緩衝區,就要記得刷新。
  //bufw.flush();

  //其實關閉緩衝區,就是在關閉緩衝區中的流對象。
  bufw.close();
 }
}

————————————————————————————————————

加強:

/*
字符讀取流緩衝區:
該緩衝區提供了一個一次讀一行的方法readLine,方便於對文本數據的獲取。
當返回null時,表示獨到文件末尾。

readLine方法返回的時候只返回回車符之前的數據內容,並不返回回車符。
*/

import java.io.*;
class BufferedReaderDemo
{
 public static void main(String[] args) throws IOException
 {
  //創建一個讀取流對象和文件相關聯。
  FileReader fr = new FileReader("buf.txt");
  
  //爲了提高效率,加入緩衝技術,將字符讀取流對象作爲參數傳遞給緩衝對象的構造函數。
  BufferedReader bufr = new BufferedReader(fr);

  String line = null;

  while((line=bufr.readLine())!=null)
  {
   System.out.println(line);
  }
  
  bufr.close();
 }
}

——————————————————————————————————

繼續加強:

/*
通過緩衝區複製一個.java文件

*/

import java.io.*;
class CopyTextByBuf
{
 public static void main(String[] args)
 {
  BufferedReader bufr = null;
  BufferedWriter bufw = null;

  try
  {
   bufr = new BufferedReader(new FileReader("BufferedWriterDemo.java"));
   bufw = new BufferedWriter(new FileWriter("bufWriter_Copy.txt"));

   String line = null;//兩個流之間的中轉站,讀一個字符就寫一個字符

   while((line=bufr.readLine())!=null)
   {
    bufw.write(line);
    bufw.newLine();
    bufw.flush();
   }
  }
  catch (IOException e)
  {
   throw new RuntimeException("讀寫失敗!");
  }
  finally
  {
   try
   {
    if(bufr!=null)
     bufr.close();
   }
   catch (IOException e)
   {
    throw new RuntimeException("讀關閉失敗!");
   }
   try
   {
    if(bufw!=null)
     bufw.close();
   }
   catch (IOException e)
   {
    throw new RuntimeException("寫入關閉失敗!");
   }
  }
 }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章