用java实现从文本文件批量导入数据至数据库

时间:2025-04-28 08:17:39

package test; 

import ;

import

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 = ();

            while (line_record != null) {

                // 解析每一条记录

                parseRecord(line_record);

                line_record = ();

            }

            System.out.println("共有合法的记录" + count + "条");

        } catch (Exception e) {

            ();

        }

    }

 

    /*

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

* 数字、email等。

     */

    private void parseRecord(String line_record) throws Exception {

     //拆分记录

        String[] fields = line_record.split(fieldLimitChar);

        if ( == 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();

            (FltNum, FltLine, FltDate, PsgName, PsgType, PsgSex,

                    PsgCab, PsgSeatNo, PsgInfo);

            count++;

        }

    }

 

    private String tranStr(String oldstr) {

        String newstr = "";

        try {

            newstr = new String(("ISO-8859-1"), "GBK");

        } catch (UnsupportedEncodingException e) {

            ();

        }

        return newstr;

    }

}