Java常見的I/O讀寫方法

目錄

0、寫在前面

本節爲軟件構造系列Chapter8中的I/O性能部分的補充。

1、I/O

Java的I/O操作比較多,具體可以查詢Java文檔,Chrome中使用Ctrl+F查詢io或nio即可。
這裏主要介紹四種比較基本I/O方式,每種讀寫大致可以分爲兩種,按行讀取和按字節讀取,整體來說,大同小異。在此實現最基本的操作。
對於下面涉及的文件地址及File對象,在下面定義:

/* in file */
String filePathIn = "file.txt";
File fileIn = new File(filePath);
/* out file */
String filePathOut = "Out.txt";
File fileOut = new File(filePathOut);
1.1、BufferedReader/Writer

使用緩存區的讀寫方式。

1.1.1、BufferedReader

這裏把brCh的大小設置爲file.length(),一次性把文件加載到緩存中,之後可以進行解析等操作;也可以設置爲特定的值(eg. 1024)等,分次加載。

      /* new FileReader(fileIn)讀寫器 */
      BufferedReader brIn = new BufferedReader(new FileReader(fileIn));
      /* 文件大小 */
      char[] brCh = new char[(int) fileIn.length()];
      /* 讀取進入brCh */
      brIn.read(brCh);
      brIn.close();
1.1.2、BufferedWriter
      BufferedWriter bwOut = new BufferedWriter(new FileWriter(fileOut));
      /* 將之前讀取的brCh數組寫入內存 */
      bwOut.write(brCh);
      bwOut.close();
1.2、nio Files

新IO操作,有很多改進,效率較高,操作較簡單。

1.2.1、read
      /* 按字節讀取 */
      byte[] nioBy = Files.readAllBytes(Paths.get(filePathIn));
      /* 一次性讀取所有行,可以使用for-each遍歷 */
      //String[] lines = Files.readAllLines(Paths.get(filePathIn));
1.2.2、write
      /* 將之前讀取的nioBy字節數組寫入內存 */
      Files.write(Paths.get(filePathOut), nioBy);
1.3、Scanner/PrintWriter
1.3.1、Scanner
      /* 創建Scanner讀取 */
      Scanner scIn = new Scanner(fileIn);
      /* 使用StringBuffer保存,避免生成太多臨時變量 */
      StringBuffer scStr = new StringBuffer();
      String scLine;
      /* 按行讀取 */
      while (scIn.hasNextLine()) {
        scLine = scIn.nextLine();
        scStr.append(scLine + "\n");
      }
      scIn.close();
1.3.2、PrintWriter
      /* 寫入器 */
      PrintWriter pwOut = new PrintWriter(fileOut);
      /* 將之前讀取保存的StringBuffer轉爲String類型,然後寫入文件 */
      pwOut.write(scStr.toString());
      pwOut.close();
1.4、Stream

使用文件流操作。

1.4.1、InputStream
      InputStream disIn = new FileInputStream(fileIn);
      /* 保存的字節數組 */
      byte dosB[] = new byte[(int) fileIn.length()];
      /* 一次加載進緩存 */
      disIn.read(dosB);
      disIn.close();
1.4.2、OutputStream
      OutputStream dosOut = new FileOutputStream(fileOut);
      /* 將讀取的字節數組寫入文件 */
      dosOut.write(dosB);
      dosOut.close();

2、性能對比

這裏寫圖片描述

參考:
javadoc

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