JAVA之NIO按行讀寫大文件,完美解決中文亂碼問題


前言

最近在開發的時候,接到了一個開發任務,要將百萬行級別的txt數據插入到數據庫中,由於內存方面的原因,因此不可能一次讀取所有內容,后來在網上找到了解決方法,可以使用NIO技術來處理,於是找到了這篇文章http://www.sharejs.com/codes/java/1334,后來在試驗過程中發現了一點小bug,由於是按字節讀取,漢字又是2個字節,因此會出現漢字讀取“一半”導致亂碼的情況,於是花了幾天時間將這個問題解決了。


例子

假設我們一次讀取的字節是從下圖的start到end,因為結尾是漢字,所以有幾率出現上述的情況。

解決方法如下:將第9行這半行(第9行陰影的部分)跟上一次讀取留下來的半行(第9行沒陰影的部分)按順序存放在字節數組,然后轉成字符串;中間第10行到第17行正常轉換成字符串;第18行這半行(第18行陰影的部分)留着跟下一次讀取的第1行(第18行沒陰影的部分)連接成一行,因為是先拼接成字節數組再轉字符串,因此不會出現亂碼的情況。



代碼

  1. package com.chillax.imp;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.io.RandomAccessFile;  
  6. import java.nio.ByteBuffer;  
  7. import java.nio.channels.FileChannel;  
  8. import java.util.ArrayList;  
  9. import java.util.Date;  
  10. import java.util.List;  
  11.   
  12. /** 
  13.  * NIO讀取百萬級別文件 
  14.  * @author Chillax 
  15.  * 
  16.  */  
  17. public class NIO {  
  18.   
  19.     public static void main(String args[]) throws Exception {  
  20.   
  21.         int bufSize = 1000000;//一次讀取的字節長度  
  22.         File fin = new File("D:\\test\\20160622_627975.txt");//讀取的文件  
  23.         File fout = new File("D:\\test\\20160622_627975_1.txt");//寫出的文件  
  24.         Date startDate = new Date();  
  25.         FileChannel fcin = new RandomAccessFile(fin, "r").getChannel();  
  26.         ByteBuffer rBuffer = ByteBuffer.allocate(bufSize);  
  27.   
  28.         FileChannel fcout = new RandomAccessFile(fout, "rws").getChannel();  
  29.         ByteBuffer wBuffer = ByteBuffer.allocateDirect(bufSize);  
  30.   
  31.         readFileByLine(bufSize, fcin, rBuffer, fcout, wBuffer);  
  32.         Date endDate = new Date();  
  33.           
  34.         System.out.print(startDate+"|"+endDate);//測試執行時間  
  35.         if(fcin.isOpen()){  
  36.             fcin.close();  
  37.         }  
  38.         if(fcout.isOpen()){  
  39.             fcout.close();  
  40.         }  
  41.     }  
  42.   
  43.     public static void readFileByLine(int bufSize, FileChannel fcin,  
  44.             ByteBuffer rBuffer, FileChannel fcout, ByteBuffer wBuffer) {  
  45.         String enter = "\n";  
  46.         List<String> dataList = new ArrayList<String>();//存儲讀取的每行數據  
  47.         byte[] lineByte = new byte[0];  
  48.           
  49.         String encode = "GBK";  
  50. //      String encode = "UTF-8";  
  51.         try {  
  52.             //temp:由於是按固定字節讀取,在一次讀取中,第一行和最后一行經常是不完整的行,因此定義此變量來存儲上次的最后一行和這次的第一行的內容,  
  53.             //並將之連接成完成的一行,否則會出現漢字被拆分成2個字節,並被提前轉換成字符串而亂碼的問題  
  54.             byte[] temp = new byte[0];  
  55.             while (fcin.read(rBuffer) != -1) {//fcin.read(rBuffer):從文件管道讀取內容到緩沖區(rBuffer)  
  56.                 int rSize = rBuffer.position();//讀取結束后的位置,相當於讀取的長度  
  57.                 byte[] bs = new byte[rSize];//用來存放讀取的內容的數組  
  58.                 rBuffer.rewind();//將position設回0,所以你可以重讀Buffer中的所有數據,此處如果不設置,無法使用下面的get方法  
  59.                 rBuffer.get(bs);//相當於rBuffer.get(bs,0,bs.length()):從position初始位置開始相對讀,讀bs.length個byte,並寫入bs[0]到bs[bs.length-1]的區域  
  60.                 rBuffer.clear();  
  61.                   
  62.                 int startNum = 0;  
  63.                 int LF = 10;//換行符  
  64.                 int CR = 13;//回車符  
  65.                 boolean hasLF = false;//是否有換行符  
  66.                 for(int i = 0; i < rSize; i++){  
  67.                     if(bs[i] == LF){  
  68.                         hasLF = true;  
  69.                         int tempNum = temp.length;  
  70.                         int lineNum = i - startNum;  
  71.                         lineByte = new byte[tempNum + lineNum];//數組大小已經去掉換行符  
  72.                           
  73.                         System.arraycopy(temp, 0, lineByte, 0, tempNum);//填充了lineByte[0]~lineByte[tempNum-1]  
  74.                         temp = new byte[0];  
  75.                         System.arraycopy(bs, startNum, lineByte, tempNum, lineNum);//填充lineByte[tempNum]~lineByte[tempNum+lineNum-1]  
  76.                           
  77.                         String line = new String(lineByte, 0, lineByte.length, encode);//一行完整的字符串(過濾了換行和回車)  
  78.                         dataList.add(line);  
  79. //                      System.out.println(line);  
  80.                         writeFileByLine(fcout, wBuffer, line + enter);  
  81.                           
  82.                         //過濾回車符和換行符  
  83.                         if(i + 1 < rSize && bs[i + 1] == CR){  
  84.                             startNum = i + 2;  
  85.                         }else{  
  86.                             startNum = i + 1;  
  87.                         }  
  88.                           
  89.                     }  
  90.                 }  
  91.                 if(hasLF){  
  92.                     temp = new byte[bs.length - startNum];  
  93.                     System.arraycopy(bs, startNum, temp, 0, temp.length);  
  94.                 }else{//兼容單次讀取的內容不足一行的情況  
  95.                     byte[] toTemp = new byte[temp.length + bs.length];  
  96.                     System.arraycopy(temp, 0, toTemp, 0, temp.length);  
  97.                     System.arraycopy(bs, 0, toTemp, temp.length, bs.length);  
  98.                     temp = toTemp;  
  99.                 }  
  100.             }  
  101.             if(temp != null && temp.length > 0){//兼容文件最后一行沒有換行的情況  
  102.                 String line = new String(temp, 0, temp.length, encode);  
  103.                 dataList.add(line);  
  104. //              System.out.println(line);  
  105.                 writeFileByLine(fcout, wBuffer, line + enter);  
  106.             }  
  107.         } catch (IOException e) {  
  108.             e.printStackTrace();  
  109.         }   
  110.     }  
  111.   
  112.     /** 
  113.      * 寫到文件上 
  114.      * @param fcout 
  115.      * @param wBuffer 
  116.      * @param line 
  117.      */  
  118.     @SuppressWarnings("static-access")  
  119.     public static void writeFileByLine(FileChannel fcout, ByteBuffer wBuffer,  
  120.             String line) {  
  121.         try {  
  122.             fcout.write(wBuffer.wrap(line.getBytes("UTF-8")), fcout.size());  
  123.         } catch (IOException e) {  
  124.             e.printStackTrace();  
  125.         }  
  126.     }  
  127. }  

—————END—————



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM