使用Java读写dbf文件

本代码使用的是javadbf-1.9.2.jar;

<dependency>
          <groupId>com.github.albfernandez</groupId>
          <artifactId>javadbf</artifactId>
          <version>1.9.2</version>
</dependency>

1.创建dbf文件

创建文件需要使用输出流,这里创建dbf文件时直接指定了字段,也可以不指定字段。

/**
	 * 创建dbf
	 * @param path:文件路径
	 * @param fieldList:字段
	 * @param charsetName编码字符集
	 * @throws IOException
	 */
	public static void createDbf(String path, List<Map<String, String>> fieldList, String charsetName) 
			throws IOException {
		DBFField[] fields = new DBFField[fieldList.size()];
		int index = 0;
		for (Map<String, String> fieldMap : fieldList) {
			DBFField field = new DBFField();
			field.setName(fieldMap.get("name"));//字段名称
			field.setType(DBFDataType.CHARACTER);//指定字段类型为字符串
			field.setLength(Integer.valueOf(fieldMap.get("length")));//指定长度
			fields[index] = field;
			index++;
		}
		//定义DBFWriter实例用来写DBF文件
        DBFWriter dbfWriter = new DBFWriter(new FileOutputStream(path), Charset.forName(charsetName));
        //设置字段
        dbfWriter.setFields(fields);
        //写入dbf文件并关闭
        dbfWriter.close();
	}

2.获取字段名

利用输入流读取dbf文件,将字段以数组形式输出,需要创建DBFReader对象

/**
	 * 获取字段名
	 * @param path
	 * @param charsetName
	 * @return
	 * @throws IOException
	 */
	public static String[] getFieldName(String path, String charsetName) throws IOException {
//		InputStream fis = new FileInputStream(path);
		DBFReader dbfReader = new DBFReader(new FileInputStream(path), Charset.forName(charsetName));
		int fieldCount = dbfReader.getFieldCount();//获取字段数量
		String[] fieldName = new String[fieldCount];
		for (int i = 0; i < fieldCount; i++) {
			fieldName[i] = dbfReader.getField(i).getName();
		}
		dbfReader.close();
//		fis.close();
		return fieldName;
	}

3.写dbf文件

写dbf文件要创建DBFWriter,DBFWriter有参构造方法,有好几个,可以传入File对象也可以传入OutputStream,当不指定字符集时将以默认字符集写入(最好指定,不然可能会出现中文乱码)。这里是先获取字段,然后根据字段进行排列值,以免出现值错位。

/**
	 * 写dbf文件
	 * @param path:dbf文件路径
	 * @param rowList:要写入的记录行
	 * @param charsetName:字符集
	 * @throws IOException
	 */
	public static void writeDbf(String path, List<Map<String, String>> rowList, String charsetName) 
			throws IOException {
		DBFWriter dbfWriter = new DBFWriter(new File(path));
		//获取字段
		String[] fieldName = getFieldName(path, "GBK");
		for (Map<String, String> rowMap : rowList) {
			Object[] rowData = new Object[fieldName.length];
			for (int i = 0; i < rowData.length; i++) {
				//根据字段来排列指,不然可能出现错位情况
				rowData[i] = rowMap.get(fieldName[i]);
			}
//			rowMap.values().toArray(rowData);
			//添加记录(此时并没有写入文件)
			dbfWriter.addRecord(rowData);
		}
		//写入dbf文件并保存关闭
		dbfWriter.close();
	}

4.读dbf记录

读取dbf文件将记录以集合的形式返回

/**
	 * 读dbf记录
	 * @param path
	 * @return
	 * @throws IOException
	 */
	public static List<Map<String, String>> readDbf(String path, String charsetName) throws IOException {  
		List<Map<String, String>> rowList = new ArrayList<>();
//		InputStream fis = new FileInputStream(path);
		DBFReader dbfReader = new DBFReader(new FileInputStream(path), Charset.forName(charsetName));
		Object[] rowValues;
		while ((rowValues = dbfReader.nextRecord()) != null) {
			Map<String, String> rowMap = new HashMap<String, String>();
			for (int i = 0; i < rowValues.length; i++) {
				rowMap.put(dbfReader.getField(i).getName(), String.valueOf(rowValues[i]).trim());
			}
//			System.out.println(rowMap);
			rowList.add(rowMap);
		}
		dbfReader.close();
//		fis.close();
		return rowList;
	}

主程序调用如下:

        try {
//            DbfWriterAndReadUtil.createDbf("b.dbf", fieldList, "GBK");
//            DbfWriterAndReadUtil.writeDbf("b.dbf", rowList, "GBK");
            String[] fieldName = DbfWriterAndReadUtil.getFieldName("b.dbf", "GBK");
            for (int i = 0; i < fieldName.length; i++) {
                System.out.println(fieldName[i]);
            }
            
            List<Map<String, String>> getRowList = DbfWriterAndReadUtil.readDbf("b.dbf", "GBK");
            for (Map<String, String> entity : getRowList) {
                System.out.println(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

  • 2
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Java中解析DBF文件可以使用Apache Commons IO和Apache Commons Lang库。以下是一个简单的示例代码,演示了如何读取DBF文件并输出其内容: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.lang3.time.DateUtils; public class DBFReader { private String fileName; private int headerLength; private int recordLength; public DBFReader(String fileName) { this.fileName = fileName; } public void read() throws IOException { FileInputStream inputStream = new FileInputStream(fileName); byte[] headerBytes = new byte[32]; IOUtils.read(inputStream, headerBytes); headerLength = NumberUtils.toInt(StringUtils.substring(headerBytes, 8, 10)); recordLength = NumberUtils.toInt(StringUtils.substring(headerBytes, 10, 12)); byte[] recordBytes = new byte[recordLength]; while (IOUtils.read(inputStream, recordBytes) != -1) { String recordString = new String(recordBytes, "ISO-8859-1"); System.out.println(recordString); } } public static void main(String[] args) throws Exception { DBFReader reader = new DBFReader("example.dbf"); reader.read(); } } ``` 这个示例代码使用了Apache Commons IO和Apache Commons Lang库来读取DBF文件。它首先读取文件头,然后使用记录长度来读取每个记录。在每个记录中,它将字节数组转换为字符串,并将其输出到控制台。请注意,DBF文件使用ISO-8859-1编码,因此我们需要使用该编码将字节数组转换为字符串。此外,我们还需要使用Apache Commons Lang库来解析整数和日期值。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值