好学IT学院:IT信息技术分享交流平台
标签:Java  来源:互联网  作者:lzkyo  发布时间:2010-03-16  ★★★加入收藏〗〖手机版
摘要:有一个项目的测试数据,要向一个表中插入上千条记录,并且保证每条记录内容不同,如果用手工一条一条插入肯定是不可能,也不会有哪个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();
    }
  }
}

  • 好学触屏公众号虎力全开、杨帆起航!
  • 四大名著全套小学生版注音版
  • 诗词中的科学全4册
  • 曹文轩系列儿童文学全套画本