本文主要是介绍dbf文件读与写,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
DBF是dBase和FoxPro软件的数据表文件
maven依赖
<!-- https://mvnrepository.com/artifact/com.github.albfernandez/javadbf -->
<dependency><groupId>com.github.albfernandez</groupId><artifactId>javadbf</artifactId><version>1.9.4</version>
</dependency>
dbf文件读取:
/*** 读取dbf文件内容* @param path dbf文件路径 + 名称* @return*/public static List<Map<String, String>> readDBF(String path) {List<Map<String, String>> result = new ArrayList<>();InputStream fis = null;try {fis = new FileInputStream(path);DBFReader reader = new DBFReader(fis);// 处理中文乱码reader.setCharactersetName("GBK");Object[] rowValues;// 一条条取出path文件中记录while ((rowValues = reader.nextRecord()) != null) {int j = 0;Map<String, String> map = new HashMap<>();for (int i = 0; i < rowValues.length; i++) {DBFField field = reader.getField(j);log.info("字段名称[{}],数据[{}]", field.getName(), rowValues[i]);map.put(field.getName(), rowValues[i] + "");j++;}result.add(map);}log.info(JSON.toJSONString(result));} catch (Exception e) {e.printStackTrace();} finally {try {fis.close();} catch (Exception e) {e.printStackTrace();}}return result;}
dbf文件的写入:
/*** 生成dbf文件* @param dbfFilePath [{"filedName":"xxx","length":"xx"},{"filedName":"xxx","length":"xx"}]* @param filedList 数据 数据格式:[[xx,xx,...],[xx,xx,...]]* @param dataList*/public static void writeDbfFile(String dbfFilePath, List<Dbf> filedList, List<List<String>> dataList) {if (filedList == null) {log.info("filedList不能为空");return;}if ("dbf".equals(dbfFilePath.lastIndexOf("."))) {throw new BusinessException("文件后缀有误");}OutputStream fos = null;DBFField fields[] = new DBFField[filedList.size()];for (int i = 0; i < filedList.size(); i++) {Dbf dbf = filedList.get(i);fields[i] = new DBFField();fields[i].setName(dbf.getFiledName());fields[i].setType(DBFDataType.CHARACTER);// 这里必须定义,指明长度fields[i].setLength(dbf.getLength());}try {DBFWriter writer = new DBFWriter();writer.setFields(fields);if (dataList != null && !dataList.isEmpty()) {dataList.forEach(data -> {Object[] rowData = new Object[dataList.size()];for (int i = 0; i < data.size(); i++) {rowData[i] = data.get(i);}writer.addRecord(rowData);});}fos = new FileOutputStream(dbfFilePath);// 解决中文乱码writer.setCharactersetName("GBK");// 写入数据writer.write(fos);log.info("dbf[{}]文件生成完成", dbfFilePath);} catch (Exception e) {e.printStackTrace();} finally {try {fos.close();} catch (Exception e) {e.printStackTrace();}}}
我的这两个方法都是写在dbfUtil类中,在这个类中我又写了一个内部类:
@Data
public static class Dbf{/** 字段名称 */private String filedName;/** 字段长度 */private int length;}
整理不易,欢迎指正。
这篇关于dbf文件读与写的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!