1. 程式人生 > >JAVA解析TXT格式文字文件

JAVA解析TXT格式文字文件

public void readRechargeWithdrawTxt(File file, Long noticeId) {
        List<CzCheckAccountInfoPO> records = new ArrayList<CzCheckAccountInfoPO>();// 
        // 將txt格式的資料存入陣列
        try {
            if (file.isFile() && file.exists()) {
                InputStreamReader isr = new InputStreamReader(
                        new FileInputStream(file), "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String lineTxt = br.readLine();// 讀取檔案的方法
                String[] firstLine = lineTxt.split("\\|"); // 讀第一行
                String withdrawCount = firstLine[0];
                String withdrawAmount = firstLine[1];
                String rechargeCount = firstLine[2];
                String rechargeAmount = firstLine[3];
                while ((lineTxt = br.readLine()) != null) {
                    String[] arrStrings = lineTxt.split("\\|"); // 用於把一個字串分割成字串陣列
                    CzCheckAccountInfoPO record = new CzCheckAccountInfoPO();

                    record.setSerialNum(String.valueOf(noticeId));
                    record.setWithdrawCount(Integer.valueOf(withdrawCount));
                    record.setWithdrawAmount(new BigDecimal(withdrawAmount));
                    record.setRechargeCount(Integer.valueOf(rechargeCount));
                    record.setRechargeAmount(new BigDecimal(rechargeAmount));

                    String ymd = arrStrings[0];
                    String hms = arrStrings[1];
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                    Date date = simpleDateFormat.parse(ymd + hms);
                    record.setTradeTime(date);
                    record.setMarketSerialNum(arrStrings[2]);
                    record.setSystemSerialNum(arrStrings[3]);
                    record.setBankCapitalNum(arrStrings[4]);
                    record.setTradeType(Integer.valueOf(arrStrings[5]));
                    record.setOriginator(Integer.valueOf(arrStrings[6]));
                    record.setAmount(new BigDecimal(arrStrings[7]));
                    record.setBalance(new BigDecimal(arrStrings[8]));
                    record.beforeInsert();
                    records.add(record); // 用set方法將取值分別新增到對應字串陣列 ,用add方法存入list

                }
                br.close();

            } else {
                System.out.println("檔案不存在!");
            }
        } catch (Exception e) {
            System.out.println("檔案讀取錯誤!");
        }

        if(records!=null &&records.size()>0){
            czCheckAccountInfoManage.batchAdd(records);
        }
    }