> 文档中心 > 使用Java读写dbf文件【附源代码】

使用Java读写dbf文件【附源代码】


📢📢📢📣📣📣

哈喽!大家好,今天给大家分享一篇如何使用Java代码解析DBF文件,获取数据。于是自己封装了一个工具类,读取DBF文件中的数据以及字段值,将读取到的数据封装成对象进行返回。

✨个人博客:https://blog.csdn.net/weixin_43759352✨

公众号:【SimpleMemory】✨

❤️❤️❤️如果有对【后端技术】感兴趣的大佬们,欢迎关注!!!❤️❤️❤️

主要代码如下:

pom.xml文件中引入所需依赖;
 

     com.github.albfernandez     javadbf     1.9.2

创建返回实体类 DBFInfo.java​​​​​​​

/** * @author 公众号: SimpleMemory * @version 1.0.0 * @ClassName DBFInfo.java * @Description DBF文件封装实体类 * @createTime 2022年02月26日 20:37:00 */@Datapublic class DBFInfo {    // 字段数量    private Integer fieldCount;    // 字段名    private String[] fieldName;    // 记录    List<Map> rowList;    //记录数量    Integer recordCount;}

核心实现类

/** * @author 公众号: SimpleMemory * @version 1.0.0 * @ClassName DBFUtils.java * @Description 读取DBF文件工具类 * @createTime 2022年02月26日 20:27:00 */@Slf4jpublic class DBFUtils {    /**     * 读取DBF文件     *     * @param filePath    文件路径     * @param charsetName     * @return     * @throws IOException     */    public static DBFInfo readDBFFile(String filePath, String charsetName) throws IOException { DBFInfo dbfInfo = new DBFInfo(); FileInputStream inputStream = null; DBFReader dbfReader = null; Object[] rowVales = null; List<Map> rowList = new ArrayList(); File file = new File(filePath); if (!file.exists()) {     log.error("文件路径:{},该文件不存在!", filePath);     return dbfInfo; } try {     log.debug("开始读取DBF文件,文件路径为: {}", filePath);     inputStream = new FileInputStream(filePath);     dbfReader = new DBFReader(inputStream, Charset.forName(charsetName), false);     // 字段数量     int fieldCount = dbfReader.getFieldCount();     log.debug("读取DBF文件,字段数量为:{}个!", fieldCount);     // 记录数量     int recordCount = dbfReader.getRecordCount();     log.debug("读取DBF文件,数据量为:{}个!", recordCount);     String[] fieldName = new String[fieldCount];     for (int i = 0; i < fieldCount; i++) {  fieldName[i] = dbfReader.getField(i).getName();     }     dbfInfo.setFieldCount(fieldCount);     dbfInfo.setFieldName(fieldName);     dbfInfo.setRecordCount(recordCount);     while ((rowVales = dbfReader.nextRecord()) != null) {  Map rowMap = new HashMap();  for (int i = 0; i < rowVales.length; i++) {      rowMap.put(dbfReader.getField(i).getName(), String.valueOf(rowVales[i]).trim());  }  rowList.add(rowMap);     }     if (CollectionUtils.isNotEmpty(rowList)) {  dbfInfo.setRowList(rowList);     }     return dbfInfo; } catch (IOException e) {     e.printStackTrace(); } catch (Exception e) {     e.printStackTrace(); } finally {     if (null != inputStream) {  inputStream.close();     }     if (null != dbfReader) {  dbfReader.close();     } } return dbfInfo;    }

如果这篇【文章】对您有帮助,希望大家点赞、评论、关注、收藏;如果对【后端技术】感兴趣的小可爱,也欢迎关注❤️❤️❤️ 公众号【SimpleMemory】❤️❤️❤️,将会继续给大家带来【收获与惊喜】💕💕!

湖北工具网