最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java多線程實現(xiàn)快速切分文件的程序

 更新時間:2016年06月08日 15:18:48   投稿:lijiao  
這篇文章主要為大家詳細(xì)介紹了Java多線程實現(xiàn)快速切分文件的相關(guān)資料,感興趣的小伙伴們可以參考一下

前段時間需要進(jìn)行大批量數(shù)據(jù)導(dǎo)入,DBA給提供的是CVS文件,但是每個CVS文件都好幾個GB大小,直接進(jìn)行l(wèi)oad,數(shù)據(jù)庫很慢還會產(chǎn)生內(nèi)存不足的問題,為了實現(xiàn)這個功能,寫了個快速切分文件的程序。

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
 
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
 
public class FileSplitUtil {
 
  private final static Logger log = LogManager.getLogger(FileSplitUtil.class);
  private static final long originFileSize = 1024 * 1024 * 100;// 100M
  private static final int blockFileSize = 1024 * 1024 * 64;// 防止中文亂碼,必須取2的N次方
  /**
   * CVS文件分隔符
   */
  private static final char cvsSeparator = '^';
  public static void main(String args[]){
    long start = System.currentTimeMillis();
    try {
      String fileName = "D:\\csvtest\\aa.csv";
      File sourceFile = new File(fileName);
      if (sourceFile.length() >= originFileSize) {
        String cvsFileName = fileName.replaceAll("\\\\", "/");
        FileSplitUtil fileSplitUtil = new FileSplitUtil();
        List<String> parts=fileSplitUtil.splitBySize(cvsFileName, blockFileSize);
        for(String part:parts){
          System.out.println("partName is:"+part);
        }
      }
      System.out.println("總文件長度"+sourceFile.length()+",拆分文件耗時:" + (System.currentTimeMillis() - start) + "ms.");
    }catch (Exception e){
      log.info(e.getStackTrace());
    }
 
  }
 
 
 
  /**
   * 拆分文件
   *
   * @param fileName 待拆分的完整文件名
   * @param byteSize 按多少字節(jié)大小拆分
   * @return 拆分后的文件名列表
   */
  public List<String> splitBySize(String fileName, int byteSize)
      throws IOException, InterruptedException {
    List<String> parts = new ArrayList<String>();
    File file = new File(fileName);
    int count = (int) Math.ceil(file.length() / (double) byteSize);
    int countLen = (count + "").length();
    RandomAccessFile raf = new RandomAccessFile(fileName, "r");
    long totalLen = raf.length();
    CountDownLatch latch = new CountDownLatch(count);
 
    for (int i = 0; i < count; i++) {
      String partFileName = file.getPath() + "."
          + leftPad((i + 1) + "", countLen, '0') + ".cvs";
      int readSize=byteSize;
      long startPos=(long)i * byteSize;
      long nextPos=(long)(i+1) * byteSize;
      if(nextPos>totalLen){
        readSize= (int) (totalLen-startPos);
      }
      new SplitRunnable(readSize, startPos, partFileName, file, latch).run();
      parts.add(partFileName);
    }
    latch.await();//等待所有文件寫完
    //由于切割時可能會導(dǎo)致行被切斷,加工所有的的分割文件,合并行
    mergeRow(parts);
    return parts;
  }
 
  /**
   * 分割處理Runnable
   *
   * @author supeidong
   */
  private class SplitRunnable implements Runnable {
    int byteSize;
    String partFileName;
    File originFile;
    long startPos;
    CountDownLatch latch;
    public SplitRunnable(int byteSize, long startPos, String partFileName,
               File originFile, CountDownLatch latch) {
      this.startPos = startPos;
      this.byteSize = byteSize;
      this.partFileName = partFileName;
      this.originFile = originFile;
      this.latch = latch;
    }
 
    public void run() {
      RandomAccessFile rFile;
      OutputStream os;
      try {
        rFile = new RandomAccessFile(originFile, "r");
        byte[] b = new byte[byteSize];
        rFile.seek(startPos);// 移動指針到每“段”開頭
        int s = rFile.read(b);
        os = new FileOutputStream(partFileName);
        os.write(b, 0, s);
        os.flush();
        os.close();
        latch.countDown();
      } catch (IOException e) {
        log.error(e.getMessage());
        latch.countDown();
      }
    }
  }
 
  /**
   * 合并被切斷的行
   *
   * @param parts
   */
  private void mergeRow(List<String> parts) {
    List<PartFile> partFiles = new ArrayList<PartFile>();
    try {
      //組裝被切分表對象
      for (int i=0;i<parts.size();i++) {
        String partFileName=parts.get(i);
        File splitFileTemp = new File(partFileName);
        if (splitFileTemp.exists()) {
          PartFile partFile = new PartFile();
          BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream(splitFileTemp),"gbk"));
          String firstRow = reader.readLine();
          String secondRow = reader.readLine();
          String endRow = readLastLine(partFileName);
          partFile.setPartFileName(partFileName);
          partFile.setFirstRow(firstRow);
          partFile.setEndRow(endRow);
          if(i>=1){
            String prePartFile=parts.get(i - 1);
            String preEndRow = readLastLine(prePartFile);
            partFile.setFirstIsFull(getCharCount(firstRow+preEndRow)>getCharCount(secondRow));
          }
 
          partFiles.add(partFile);
          reader.close();
        }
      }
      //進(jìn)行需要合并的行的寫入
      for (int i = 0; i < partFiles.size() - 1; i++) {
        PartFile partFile = partFiles.get(i);
        PartFile partFileNext = partFiles.get(i + 1);
        StringBuilder sb = new StringBuilder();
        if (partFileNext.getFirstIsFull()) {
          sb.append("\r\n");
          sb.append(partFileNext.getFirstRow());
        } else {
          sb.append(partFileNext.getFirstRow());
        }
        writeLastLine(partFile.getPartFileName(),sb.toString());
      }
    } catch (Exception e) {
      log.error(e.getMessage());
    }
  }
 
  /**
   * 得到某個字符出現(xiàn)的次數(shù)
   * @param s
   * @return
   */
  private int getCharCount(String s) {
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
      if (s.charAt(i) == cvsSeparator) {
        count++;
      }
    }
    return count;
  }
 
  /**
   * 采用BufferedInputStream方式讀取文件行數(shù)
   *
   * @param filename
   * @return
   */
  public int getFileRow(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    byte[] c = new byte[1024];
    int count = 0;
    int readChars = 0;
    while ((readChars = is.read(c)) != -1) {
      for (int i = 0; i < readChars; ++i) {
        if (c[i] == '\n')
          ++count;
      }
    }
    is.close();
    return count;
  }
 
  /**
   * 讀取最后一行數(shù)據(jù)
   * @param filename
   * @return
   * @throws IOException
   */
  private String readLastLine(String filename) throws IOException {
    // 使用RandomAccessFile , 從后找最后一行數(shù)據(jù)
    RandomAccessFile raf = new RandomAccessFile(filename, "r");
    long len = raf.length();
    String lastLine = "";
    if(len!=0L) {
      long pos = len - 1;
      while (pos > 0) {
        pos--;
        raf.seek(pos);
        if (raf.readByte() == '\n') {
          lastLine = raf.readLine();
          lastLine=new String(lastLine.getBytes("8859_1"), "gbk");
          break;
        }
      }
    }
    raf.close();
    return lastLine;
  }
  /**
   * 修改最后一行數(shù)據(jù)
   * @param fileName
   * @param lastString
   * @return
   * @throws IOException
   */
  private void writeLastLine(String fileName,String lastString){
    try {
      // 打開一個隨機(jī)訪問文件流,按讀寫方式
      RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
      // 文件長度,字節(jié)數(shù)
      long fileLength = randomFile.length();
      //將寫文件指針移到文件尾。
      randomFile.seek(fileLength);
      //此處必須加gbk,否則會出現(xiàn)寫入亂碼
      randomFile.write(lastString.getBytes("gbk"));
      randomFile.close();
    } catch (IOException e) {
      log.error(e.getMessage());
    }
  }
  /**
   * 左填充
   *
   * @param str
   * @param length
   * @param ch
   * @return
   */
  public static String leftPad(String str, int length, char ch) {
    if (str.length() >= length) {
      return str;
    }
    char[] chs = new char[length];
    Arrays.fill(chs, ch);
    char[] src = str.toCharArray();
    System.arraycopy(src, 0, chs, length - src.length, src.length);
    return new String(chs);
  }
 
  /**
   * 合并文件行內(nèi)部類
   */
  class PartFile {
    private String partFileName;
    private String firstRow;
    private String endRow;
    private boolean firstIsFull;
 
    public String getPartFileName() {
      return partFileName;
    }
 
    public void setPartFileName(String partFileName) {
      this.partFileName = partFileName;
    }
 
    public String getFirstRow() {
      return firstRow;
    }
 
    public void setFirstRow(String firstRow) {
      this.firstRow = firstRow;
    }
 
    public String getEndRow() {
      return endRow;
    }
 
    public void setEndRow(String endRow) {
      this.endRow = endRow;
    }
 
    public boolean getFirstIsFull() {
      return firstIsFull;
    }
 
    public void setFirstIsFull(boolean firstIsFull) {
      this.firstIsFull = firstIsFull;
    }
  }
 
}

以上就是本文的全部內(nèi)容,希望對大家學(xué)習(xí)java程序設(shè)計有所幫助。

相關(guān)文章

  • springAOP完整實現(xiàn)過程

    springAOP完整實現(xiàn)過程

    當(dāng)你調(diào)用SimpleService類的doSomething方法時,上述的PerformanceAspect會自動攔截此調(diào)用,并且記錄該方法的執(zhí)行時間,這樣你就完成了一個針對Spring的AOP入門級案例,感興趣的朋友一起看看吧
    2024-02-02
  • JavaIO?BufferedReader和BufferedWriter使用及說明

    JavaIO?BufferedReader和BufferedWriter使用及說明

    這篇文章主要介紹了JavaIO?BufferedReader和BufferedWriter使用及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • Java動態(tài)規(guī)劃之硬幣找零問題實現(xiàn)代碼

    Java動態(tài)規(guī)劃之硬幣找零問題實現(xiàn)代碼

    這篇文章主要介紹了Java動態(tài)規(guī)劃之硬幣找零問題實現(xiàn)代碼,具有一定參考價值,需要的朋友可以了解下。
    2017-11-11
  • java web返回中文亂碼問題及解決

    java web返回中文亂碼問題及解決

    這篇文章主要介紹了java web返回中文亂碼問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • springboot通過spel結(jié)合aop實現(xiàn)動態(tài)傳參的案例

    springboot通過spel結(jié)合aop實現(xiàn)動態(tài)傳參的案例

    SpEl 是Spring框架中的一個利器,Spring通過SpEl能在運行時構(gòu)建復(fù)雜表達(dá)式、存取對象屬性、對象方法調(diào)用等,今天通過本文給大家介紹springboot?spel結(jié)合aop實現(xiàn)動態(tài)傳參,需要的朋友可以參考下
    2022-07-07
  • 詳解Nacos中注冊中心和配置中心的實現(xiàn)

    詳解Nacos中注冊中心和配置中心的實現(xiàn)

    Spring?Cloud?Alibaba?是阿里巴巴提供的一站式微服務(wù)開發(fā)解決方案。而?Nacos?作為?Spring?Cloud?Alibaba?的核心組件之一,提供了兩個非常重要的功能:注冊中心和配置中心,我們今天來了解和實現(xiàn)一下二者
    2022-08-08
  • 關(guān)于工廠方法模式的Java實現(xiàn)

    關(guān)于工廠方法模式的Java實現(xiàn)

    這篇文章主要介紹了關(guān)于工廠方法模式的Java實現(xiàn)講解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • SpringBoot中的@CrossOrigin注解詳解

    SpringBoot中的@CrossOrigin注解詳解

    這篇文章主要介紹了SpringBoot中的@CrossOrigin注解詳解,跨源資源共享(CORS)是由大多數(shù)瀏覽器實現(xiàn)的W3C規(guī)范,允許您靈活地指定什么樣的跨域請求被授權(quán),而不是使用一些不太安全和不太強(qiáng)大的策略,需要的朋友可以參考下
    2023-11-11
  • springboot項目中idea的pom.xml文件的引用標(biāo)簽全部爆紅問題解決

    springboot項目中idea的pom.xml文件的引用標(biāo)簽全部爆紅問題解決

    這篇文章主要介紹了springboot項目中idea的pom.xml文件的引用標(biāo)簽全部爆紅問題解決,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),需要的朋友參考下吧
    2023-12-12
  • IDEA 2023創(chuàng)建JSP項目的完整步驟教程

    IDEA 2023創(chuàng)建JSP項目的完整步驟教程

    這篇文章主要介紹了IDEA 2023創(chuàng)建JSP項目的完整步驟教程,創(chuàng)建項目需要經(jīng)過新建項目、設(shè)置項目名稱和路徑、選擇JDK版本、添加模塊和工件、配置Tomcat服務(wù)器等步驟,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2024-10-10

最新評論

蓝山县| 阜康市| 丰顺县| 凤阳县| 恩平市| 罗源县| 永吉县| 潮安县| 太仆寺旗| 安龙县| 潼关县| 左云县| 和田县| 防城港市| 锦屏县| 正宁县| 昌图县| 衡南县| 连州市| 亳州市| 乳源| 唐山市| 印江| 满城县| 开原市| 咸阳市| 韩城市| 海丰县| 鹤峰县| 龙南县| 晋州市| 永福县| 榆社县| 裕民县| 攀枝花市| 灯塔市| 古浪县| 丰顺县| 昌黎县| 新余市| 重庆市|