1.nio实现读取大文件,之后分批读取写入数据库

2.nio实现读取大文件,之后分批写入指定文件

  1. package com.ally;
  2. import java.io.File;
  3. import java.io.RandomAccessFile;
  4. import java.nio.ByteBuffer;
  5. import java.nio.channels.FileChannel;
  6. import java.sql.*;
  7. /**
  8. * Created by admin on 2016/6/28.
  9. * 1.nio分批读取sql文件并执行插入数据库
  10. * 2.读取一个文件写入另外文件
  11. */
  12. public class TestNio {
  13. public static void main(String args[]) throws Exception {
  14. System.err.println("begin");
  15. long start = System.currentTimeMillis();
  16. int _5M = 1024 * 1024 * 5;
  17. File fin = new File("D:\\drug_general_info.sql");
  18. FileChannel fcin = new RandomAccessFile(fin, "r").getChannel();
  19. ByteBuffer rBuffer = ByteBuffer.allocate(_5M);
  20. //将文件读取执行到数据库
  21. readFileByLine(_5M, fcin, rBuffer);
  22. //将文件读取并写入另外文件
  23. File fout = new File("D:\\mm.sql");
  24. FileChannel fcout = new RandomAccessFile(fout, "rws").getChannel();
  25. ByteBuffer wBuffer = ByteBuffer.allocateDirect(_5M);
  26. saveOtherFile( _5M,  fcin, rBuffer,  fcout,  wBuffer);
  27. System.err.print((System.currentTimeMillis() - start) / 1000);
  28. }
  29. /**
  30. * 将一个文件内容写入另外一个
  31. * @param bufSize
  32. * @param fcin
  33. * @param rBuffer
  34. * @param fcout
  35. * @param wBuffer
  36. */
  37. public static void saveOtherFile(int bufSize, FileChannel fcin,
  38. ByteBuffer rBuffer, FileChannel fcout, ByteBuffer wBuffer){
  39. Statement pst = null;
  40. String enterStr = "\n";
  41. try {
  42. byte[] bs = new byte[bufSize];
  43. StringBuilder strBuf = new StringBuilder("");
  44. String tempString = null;
  45. while (fcin.read(rBuffer) != -1) {
  46. int rSize = rBuffer.position();
  47. rBuffer.rewind();
  48. rBuffer.get(bs);
  49. rBuffer.clear();
  50. tempString = new String(bs, 0, rSize);
  51. int fromIndex = 0;
  52. int endIndex = 0;
  53. int i = 0;
  54. while ((endIndex = tempString.indexOf(enterStr, fromIndex)) != -1) {
  55. String line = tempString.substring(fromIndex, endIndex);
  56. line = strBuf.toString() + line;
  57. writeFileByLine(fcout, wBuffer, line);
  58. strBuf.delete(0, strBuf.length());
  59. fromIndex = endIndex + 1;
  60. }
  61. }
  62. } catch (Exception e) {
  63. e.printStackTrace();
  64. }
  65. }
  66. /**
  67. * 读文件写入数据库
  68. * @param bufSize
  69. * @param fcin
  70. * @param rBuffer
  71. */
  72. public static void readFileByLine(int bufSize, FileChannel fcin,
  73. ByteBuffer rBuffer) {
  74. Connection conn = null;
  75. Statement pst = null;
  76. String enterStr = "\n";
  77. try {
  78. byte[] bs = new byte[bufSize];
  79. StringBuilder strBuf = new StringBuilder("");
  80. String tempString = null;
  81. Class.forName("com.mysql.jdbc.Driver");
  82. conn = DriverManager.getConnection(
  83. "jdbc:mysql://localhost:3306/doctor?useUnicode=true&characterEncoding=utf-8", "root", "root");
  84. pst = conn.createStatement();
  85. while (fcin.read(rBuffer) != -1) {
  86. int rSize = rBuffer.position();
  87. rBuffer.rewind();
  88. rBuffer.get(bs);
  89. rBuffer.clear();
  90. tempString = new String(bs, 0, rSize);
  91. int fromIndex = 0;
  92. int endIndex = 0;
  93. int i = 0;
  94. while ((endIndex = tempString.indexOf(enterStr, fromIndex)) != -1) {
  95. String line = tempString.substring(fromIndex, endIndex);
  96. line = strBuf.toString() + line;
  97. strBuf.delete(0, strBuf.length());
  98. fromIndex = endIndex + 1;
  99. pst.addBatch(line);
  100. /*  System.out.println("-----------------------");
  101. System.out.println(line);
  102. System.out.println("-----------------------");*/
  103. if (i % 100 == 0) {
  104. System.out.println("执行了:" + i);
  105. if (i == 2700) {
  106. System.out.println("导了:" + i);
  107. }
  108. int[] flag = pst.executeBatch();
  109. System.out.println("结果:" + flag[0]);
  110. }
  111. i += 1;
  112. }
  113. // 执行批量更新
  114. pst.executeBatch();
  115. if (rSize > tempString.length()) {
  116. strBuf.append(tempString.substring(fromIndex,
  117. tempString.length()));
  118. } else {
  119. strBuf.append(tempString.substring(fromIndex, rSize));
  120. }
  121. //  System.out.println(strBuf.toString());
  122. }
  123. } catch (Exception e) {
  124. e.printStackTrace();
  125. } finally {
  126. try {
  127. if (pst != null) {
  128. pst.close();
  129. }
  130. if (conn != null) {
  131. conn.close();
  132. }
  133. } catch (SQLException e) {
  134. e.printStackTrace();
  135. }
  136. }
  137. }
  138. public static void writeFileByLine(FileChannel fcout, ByteBuffer wBuffer,
  139. String line) {
  140. try {
  141. fcout.write(wBuffer.wrap(line.getBytes()), fcout.size());
  142. } catch (Exception e) {
  143. e.printStackTrace();
  144. }
  145. }
  146. }
package com.ally;

import java.io.File;

import java.io.RandomAccessFile;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

import java.sql.*; /**
  • Created by admin on 2016/6/28.
  • 1.nio分批读取sql文件并执行插入数据库
  • 2.读取一个文件写入另外文件

    */

    public class TestNio {

    public static void main(String args[]) throws Exception {

    System.err.println("begin");

    long start = System.currentTimeMillis();

    int _5M = 1024 * 1024 * 5;

    File fin = new File("D:\drug_general_info.sql");

    FileChannel fcin = new RandomAccessFile(fin, "r").getChannel();

    ByteBuffer rBuffer = ByteBuffer.allocate(_5M);

    //将文件读取执行到数据库

    readFileByLine(_5M, fcin, rBuffer);
     //将文件读取并写入另外文件
    File fout = new File("D:\\mm.sql");
    FileChannel fcout = new RandomAccessFile(fout, "rws").getChannel();
    ByteBuffer wBuffer = ByteBuffer.allocateDirect(_5M);
    saveOtherFile( _5M, fcin, rBuffer, fcout, wBuffer);
    System.err.print((System.currentTimeMillis() - start) / 1000);

    }

    /**

    • 将一个文件内容写入另外一个

    • @param bufSize

    • @param fcin

    • @param rBuffer

    • @param fcout

    • @param wBuffer

      */

      public static void saveOtherFile(int bufSize, FileChannel fcin,

      ByteBuffer rBuffer, FileChannel fcout, ByteBuffer wBuffer){

      Statement pst = null;

      String enterStr = "\n";

      try {

      byte[] bs = new byte[bufSize];

      StringBuilder strBuf = new StringBuilder("");

      String tempString = null;

      while (fcin.read(rBuffer) != -1) {

      int rSize = rBuffer.position();

      rBuffer.rewind();

      rBuffer.get(bs);

      rBuffer.clear();

      tempString = new String(bs, 0, rSize);

      int fromIndex = 0;

      int endIndex = 0;

      int i = 0;

      while ((endIndex = tempString.indexOf(enterStr, fromIndex)) != -1) {

      String line = tempString.substring(fromIndex, endIndex);

      line = strBuf.toString() + line;

      writeFileByLine(fcout, wBuffer, line);

      strBuf.delete(0, strBuf.length());

      fromIndex = endIndex + 1;

               }
      }
      } catch (Exception e) {
      e.printStackTrace();
      }

    }

    /**

    • 读文件写入数据库

    • @param bufSize

    • @param fcin

    • @param rBuffer

      */

      public static void readFileByLine(int bufSize, FileChannel fcin,

      ByteBuffer rBuffer) {

      Connection conn = null;

      Statement pst = null;

      String enterStr = "\n";

      try {

      byte[] bs = new byte[bufSize];

      StringBuilder strBuf = new StringBuilder("");

      String tempString = null;

      Class.forName("com.mysql.jdbc.Driver");

      conn = DriverManager.getConnection(

      "jdbc:mysql://localhost:3306/doctor?useUnicode=true&characterEncoding=utf-8", "root", "root");

      pst = conn.createStatement();

      while (fcin.read(rBuffer) != -1) {

           int rSize = rBuffer.position();
      rBuffer.rewind();
      rBuffer.get(bs);
      rBuffer.clear();
      tempString = new String(bs, 0, rSize);
      int fromIndex = 0;
      int endIndex = 0;
      int i = 0;
      while ((endIndex = tempString.indexOf(enterStr, fromIndex)) != -1) {
      String line = tempString.substring(fromIndex, endIndex);
      line = strBuf.toString() + line;
      strBuf.delete(0, strBuf.length());
      fromIndex = endIndex + 1;
      pst.addBatch(line);
      /* System.out.println("-----------------------");
      System.out.println(line);
      System.out.println("-----------------------");*/
      if (i % 100 == 0) {
      System.out.println("执行了:" + i);
      if (i == 2700) {
      System.out.println("导了:" + i);
      }
      int[] flag = pst.executeBatch();
      System.out.println("结果:" + flag[0]);
      }
      i += 1;
      }
      // 执行批量更新
      pst.executeBatch(); if (rSize > tempString.length()) {
      strBuf.append(tempString.substring(fromIndex,
      tempString.length()));
      } else {
      strBuf.append(tempString.substring(fromIndex, rSize));
      }
      // System.out.println(strBuf.toString());
      }

      } catch (Exception e) {

      e.printStackTrace();

      } finally {

      try {

      if (pst != null) {

      pst.close();

      }

      if (conn != null) {

      conn.close();

      }

      } catch (SQLException e) {

      e.printStackTrace();

      }

      }

      }

    public static void writeFileByLine(FileChannel fcout, ByteBuffer wBuffer,

    String line) {

    try {

    fcout.write(wBuffer.wrap(line.getBytes()), fcout.size());

    } catch (Exception e) {

    e.printStackTrace();

    }

    }

    }

nio实现文件读取写入数据库或文件的更多相关文章

  1. PostgreSql那点事(文件读取写入、命令执行的办法)

    • 2013/07/9 作者: admin PostgreSql那点事(文件读取写入.命令执行的办法) 今天无意发现了个PostgreSQL环境,线上学习了下,一般的数据注射(读写数据库)差异不大,不 ...

  2. xml文件读取到数据库

    xml文件读取到数据库   第一步,导包 c3p0,dom4j,jaxen,MySQL-connector 第二步  xml文件,config文件 第三步 javabean 第四步 c3p0的工具类 ...

  3. Excel 读取写入数据库

    // Excel 读取写入数据库 // 3.8版本的poi  4.0 可以不用写  parseCell  这个方法,可以直接赋值 STRING 类型 import org.apache.poi.hss ...

  4. SpringBoot读取Linux服务器某路径下文件\读取项目Resource下文件

    // SpringBoot读取Linux服务器某路径下文件 public String messageToRouted() { File file = null; try { file = Resou ...

  5. (OAF)jdeveloper集成log4j并将日志输出到指定文件并写入数据库

    参考: How to configure Log4j in JDev 11g Ever wanted to use log4j in your adf project ? Well though Or ...

  6. python向config、ini文件读取写入

    config读取操作 cf = configparser.ConfigParser() # 实例化对象 cf.read(filename) # 读取文件 cf.sections() # 读取secti ...

  7. html外部文件读取/写入

    1.文件的读取 外部文件读取控件: <input type="file" id="file_jquery" onchange="file_jqu ...

  8. python学习笔记6-输入输出与文件读取写入

    (1)打印到屏幕:print (2)读取键盘输入:input/raw_input #键盘输入 str = raw_input("Please enter:"); print (&q ...

  9. shell cat 合并文件,合并数据库sql文件

    > 覆盖写入 >> append模式写入 ###################################################################合并数 ...

随机推荐

  1. Linux/UNIX线程(1)

    线程(1) 本文将介绍怎样使用多个控制线程在单个进程环境中运行多个任务. 一个进程中的全部线程都能够訪问该进程的组成部件(如文件描写叙述符和内存). 线程包含了表示进程内运行环境必须的信息,当中包含进 ...

  2. gcc 源代码下载地址

    ftp://mirrors-usa.go-parts.com/gcc/releases/

  3. GPU开发笔记(一)

    首先我想到的是把安装好的CUDA下的programdata里面的demo都找一找,看看有没有自己需要的demo程序. 然后去CSDN或者pudn上去找找开源的代码. 至于GITHUB还没找过. 其次是 ...

  4. asp.net网页播放MP4 出错

    通过IIS进行添加:单击[开始]→[程序]→[管理工具]→[IIS管 理器],逐步展开“本地计算机”.“网站”,在你的网站上右击,选择[属性],单击“HTTP头”选项卡→单击“MIME类型”按钮,再单 ...

  5. 51Nod 活动安排问题(排序+优先队列)

    有若干个活动,第i个开始时间和结束时间是[Si,fi),同一个教室安排的活动之间不能交叠,求要安排所有活动,最少需要几个教室? Input 第一行一个正整数n (n <= 10000)代表活动的 ...

  6. BZOJ 3639: Query on a tree VII LCT_set维护子树信息

    用 set 维护子树信息,细节较多. Code: #include <cstring> #include <cstdio> #include <algorithm> ...

  7. pc端如何引用日期插件

    页面的html部分 <li> <span>出生日期</span> <input type="text" placeholder=" ...

  8. vue中的三级联动

    1.template里面的内容 2.js里面的内容 3.函数怎么写? 这是一个省市区的三级联动,首先你要传递中国的id,这样才能获取到所有的省份,所以在vue的项目中,我需要发一次进页面就请求(来得到 ...

  9. XAMPP添加多个站点之httpd-vhosts.conf 设置

    1.在xampp\apache\conf\httpd.conf设置路径DocumentRoot和Directory 必须与xampp\apache\conf\extra\httpd-vhosts.co ...

  10. div和css:行内元素和块元素的水平和垂直居中

    行内元素: 水平居中:text-align:center ul水平居中:加 display:table; margin:0 auto; 此元素会作为块级表格来显示(类似 <table>), ...