小工具系列第二篇来啦~
这篇是解决测试解析txt相关的需求造数的问题。
一、产品需求
我们需要将合作方放到sftp的txt文件拉回来,并且解析txt,存入数据库。
根据产品需求,我需要将准备好的txt文件放到sftp上面,并且核对解析的txt入库是否正确。
二、具体实现
1、合作方一般会把txt的demo放到sftp,并且会给到我们接口文档,接口文档会描述每个字段的意思、类型、长度、是否必填等等,但是在txt的数据是没有表头的!!!需要对着文档和txt来查看,如果一个txt字段很多,并且一次测试一般会设计3个及以上的txt,简直头秃!
那么如何方便我们核对数据呢?必然是有表头并且方便编辑,一个合适的方式就将txt转换为csv并写入表头。
public static void txtToCsv(String txtFilePath,String csvFilePath) {
File file = new File(txtFilePath);
System.out.println(txtFilePath);
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
try {
CsvWriter csvWriter = new CsvWriter(csvFilePath, ',', Charset.forName("UTF-8"));
// 写入表头
// String line[] = {"银行借据编号", "还款期次", "还款总金额", "还款本金", "还款利息", "还款罚息", "还款复息", "还款手续费", "还款日期", "交易时间", "还款类型", "贷款回收方式", "当期结清状态", "渠道还款请求流水号", "渠道放款请求流水号"};
String line[] = {"借据编号", "还款交易流水号", "分期数", "还款对应期数", "应还款日期", "实际还款日期", "还款总额", "还款本金", "还款利息", "还款罚息", "还款类型", "保费", "对账日期"};
csvWriter.writeRecord(line);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String string = "";
while ((string = bufferedReader.readLine()) != null) {
String[] s = string.split("\\|"); // | 需要转义
System.out.println(s[0]);
csvWriter.writeRecord(s);
}
csvWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}2、在csv里面对着表头造数还是很友好的!当我们在csv里面修改好数据之后,又需要将csv转换为txt,注意需要去掉表头,将csv里面的,转换为|。
public static void readCsvWriteToTxt(String csvFilePath,String txtFilePath) throws Exception {
ArrayList<String> csvList = new ArrayList<String>();
CsvReader csvReader = new CsvReader(csvFilePath, ',', Charset.forName("GBK"));
csvReader.readHeaders(); //跳过表头,不跳可以注释掉
while (csvReader.readRecord()) {
String line = csvReader.getRawRecord(); //按行读取
csvList.add(csvReader.getRawRecord()); //把每一行的数据添加到csvList集合
System.out.println("读取csv的值:" + line);
}
System.out.println("\n" + "读取的行数:" + csvList.size() + "\n");
csvReader.close();
File file = new File(txtFilePath);
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bw =new BufferedWriter(fileWriter);
for(int i=0;i<csvList.size();i++){
bw.write(csvList.get(i).replace(',','|'));
//换行
bw.newLine();
System.out.println("写入txt的值:"+ csvList.get(i).replace(',','|'));
}
bw.close();
}3、最后将txt通过SftpUtils将转换后的txt传送到sftp。只要修改csv,调一下主方法,即可快速方便的造好测试数据啦~是不是很nice~
三、总结
遇到繁琐的事情不要烦,三思而后行,先提炼出自己的需求,再逐步拆解,将重复的步骤利用工具解决~思路是最重要的。