用java实现从文本文件批量导入数据的方法

来源:互联网  作者:lzkyo
摘要:有一个项目的测试数据,要向一个表中插入上千条记录,并且保证每条记录内容不同,如果用手工一条一条插入肯定是不可能,也不会有哪个SB去做这样的事,我最开始想到了用循环,但要求插入的记录内容不能相同,用循环实现比较麻烦,于是我想到了将记录从文本文件导入至数据库(其实…

2》数据采集类DataGather.java

package test;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
public class DataGather {
  private static final String path = "src/resource/test";
  public static final String openFileStyle = "r";
  public static final String fieldLimitChar = ",";
  public static final int fieldAllCount = 9;
  private int count;
  private String FltNum;
  private String FltLine;
  private String FltDate;
  private String PsgName;
  private String PsgType;
  private String PsgSex;
  private String PsgCab;
  private String PsgSeatNo;
  private String PsgInfo;

/*
  * 功能:解析文本文件
  */
  public void loadFile() {
    try {
      RandomAccessFile raf = new RandomAccessFile(path, openFileStyle);
      String line_record = raf.readLine();
      while (line_record != null) {
        // 解析每一条记录
        parseRecord(line_record);
        line_record = raf.readLine();
      }
      System.out.println("共有合法的记录" + count + "条");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

/*
* 功能:具体解析每一条记录,这里可以增加很多对记录的解析判断条件,如是否为字母、
* 数字、email等。
  */

private void parseRecord(String line_record) throws Exception {
  //拆分记录
    String[] fields = line_record.split(fieldLimitChar);
    if (fields.length == fieldAllCount) {
      FltNum = tranStr(fields[0]);
      FltLine = tranStr(fields[1]);
      FltDate = tranStr(fields[2]);
      PsgName = tranStr(fields[3]);
      PsgType = tranStr(fields[4]);
      PsgSex = tranStr(fields[5]);
      PsgCab = tranStr(fields[6]);
      PsgSeatNo = tranStr(fields[7]);
      PsgInfo = tranStr(fields[8]);
      System.out.println(FltNum + " " + FltLine + " " + FltDate + " "
          + PsgName + " " + PsgType + " " + PsgSex + " " + PsgCab
          + " " + PsgSeatNo + " " + PsgInfo);
      InsertDB db = new InsertDB();
      db.insertDB(FltNum, FltLine, FltDate, PsgName, PsgType, PsgSex,
          PsgCab, PsgSeatNo, PsgInfo);
      count++;
    }
  }

private String tranStr(String oldstr) {
    String newstr = "";
    try {
      newstr = new String(oldstr.getBytes("ISO-8859-1"), "GBK");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return newstr;
  }
}

3》测试类Test.java

package test;
public class Test {
  public static void main(String[] args) {
    try {
      DataGather gather = new DataGather ();
      gather.loadFile();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

【相关文章】好搜一下
关于J2EE开发中OutOfMemoryError错误的解决方案

关于J2EE开发中OutOfMemoryEr

myeclipse中分配tomcat启动时所占内存大小+java.lang.Ou…