1. 程式人生 > >java程式碼實現CSV檔案讀取、將資料拆分成多個CSV檔案及資料匯出到CSV檔案

java程式碼實現CSV檔案讀取、將資料拆分成多個CSV檔案及資料匯出到CSV檔案

package com.cn;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import scala.collection.mutable.StringBuilder;

/**
 * 1.CSV檔案讀取;
 * 2.將資料拆分成多個CSV檔案;
 * 3.將資料匯出到CSV檔案;
 * @author Dabria_ly 2017年8月16日
 */
public class TestCSVUtil {
	public static void main(String[] args) throws IOException {
		 long startTime = System.currentTimeMillis();    //獲取開始時間
		//1.讀取CSV檔案資料
		 BufferedReader br = new BufferedReader(
			   		new InputStreamReader(new FileInputStream("D:/test/lendon2.csv"),"GBK")//設定編碼讀取方式為GBK
			   	 );      					    	    				 			   

		 String line;
		 String mobile;
		 String borrowerid;
		 
		 List<String> li = new ArrayList<String>();
		 while((line = br.readLine()) != null ) {
			   //讀取獲取CSV檔案行、列資料
			   String[] info = line.split(",");
			   
			  /*
			   * 本地列印可以在此設定字符集編碼 
			   mobile = new String(info[2].trim().getBytes("GBK"), "UTF-8");
			   borrowerid = new String(info[4].trim().getBytes("GBK"), "UTF-8");*/
			   
			   //匯出到csv檔案可以直接在匯出是設定OutputStreamWriter的字符集編碼為UTF-8
			   mobile = new String(info[2].trim());
			   borrowerid = new String(info[4].trim());
			   //將資料拼成字串拼接格式
			   li.add(new StringBuilder().append(mobile).append(",").append(borrowerid).toString());

		  }  
		   
		   //2.將33w條資料匯出到11個CSV檔案中
		   //設定11個CSV檔案的檔名
		   String[] csvName = new String[11];
		   for (int i = 0; i < csvName.length; i++) {
			   csvName[i] = new StringBuilder().append("D:/test/ld").append(i+1).append(".csv").toString();
		   }
		   
		  //列印11個檔名名稱
		   System.out.println("11個檔名名稱分別為-->");
		   for (int i = 0; i < csvName.length; i++) {
			   System.out.print(csvName[i]+"\n");
		   }
		   
		   //3.將集合資料匯出到11個小CSV檔案中
		   boolean[] allSuccess = new boolean[csvName.length];
		   for(int i = 1; i<=csvName.length;i++){
			   boolean isSuccess = false;
			   	//每次匯出一萬條資料到CSV檔案
			   if(i == 11){
				   isSuccess=exportCsv(new File(csvName[i-1]), li.subList((i-1)*30000, li.size()));
			   }else{
				   isSuccess=exportCsv(new File(csvName[i-1]), li.subList((i-1)*30000, i*30000));  
			   }
				allSuccess[i-1] = isSuccess;
		   }
		   
		   //列印11個檔案每次資料匯出成功與否
		   System.out.println("11個檔案每次資料匯出成功與否-->");
		   for (int i = 0; i < allSuccess.length; i++) {
			   System.out.print(allSuccess[i]+",");
		   }
		   
		   long endTime = System.currentTimeMillis();    //獲取結束時間
		   double userTime = ((double)endTime - startTime)/1000;//執行時長<秒>
		   System.out.println("\n"+String.format("執行完畢,共花時長:%s秒", userTime));//秒
	}
	
	 /**
    * 匯出(到CSV檔案)
    * @param file csv檔案(路徑+檔名),csv檔案不存在會自動建立
    * @param dataList 資料
    * @return
    */
   public static boolean exportCsv(File file, List<String> dataList){
       boolean isSucess=false;
       
       FileOutputStream out=null;
       OutputStreamWriter osw=null;
       BufferedWriter bw=null;
       try {
           out = new FileOutputStream(file);
           osw = new OutputStreamWriter(out,"UTF-8");//設定輸出編碼方式為UTF-8
           //加上UTF-8檔案的標識字元
           osw.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF }));
           
           bw =new BufferedWriter(osw);
           if(dataList!=null && !dataList.isEmpty()){
               for(String data : dataList){
                   bw.append(data).append("\r");
               }
           }
           isSucess=true;
       } catch (Exception e) {
           isSucess=false;
       }finally{
           if(bw!=null){
               try {
                   bw.close();
                   bw=null;
               } catch (IOException e) {
                   e.printStackTrace();
               } 
           }
           if(osw!=null){
               try {
                   osw.close();
                   osw=null;
               } catch (IOException e) {
                   e.printStackTrace();
               } 
           }
           if(out!=null){
               try {
                   out.close();
                   out=null;
               } catch (IOException e) {
                   e.printStackTrace();
               } 
           }
       }
       
       return isSucess;
   }
}
//-------執行結果-------
11個檔名名稱分別為-->
D:/test/ld1.csv
D:/test/ld2.csv
D:/test/ld3.csv
D:/test/ld4.csv
D:/test/ld5.csv
D:/test/ld6.csv
D:/test/ld7.csv
D:/test/ld8.csv
D:/test/ld9.csv
D:/test/ld10.csv
D:/test/ld11.csv
11個檔案每次資料匯出成功與否-->
true,true,true,true,true,true,true,true,true,true,true,
執行完畢,共花時長:0.389秒