DBF文件格式是一种比较“古老”的数据库文件格式了。要不是最近项目中需要,笔者恐怕到今天也不曾听说过DBF文件格式。
作用:DBF数据库格式是DOS系统中的dBase数据库和FoxPro数据库所使用的数据库格式。如今,如果电脑上没有安装这两款软件,可以使用Excel打开。
package zj.jdbc.util; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import com.linuxense.javadbf.DBFDataType; import com.linuxense.javadbf.DBFField; import com.linuxense.javadbf.DBFReader; import com.linuxense.javadbf.DBFWriter; import zj.check.util.CheckUtil; import zj.common.exception.ServiceException; import zj.io.util.FileUtil; import zj.java.util.JavaUtil; import zj.jdbc.bean.DBFRead; import zj.jdbc.bean.DBFWrite; import zj.reflect.util.TypeUtil; /** * 类名 :DBFUtil<br> * * @version 1.00 (2014.09.15) * @author SHNKCS 张军 {@link <a target=_blank href="http://www.zhangjunbk.com">上海加盾信息科技有限公司</a> <a target=_blank href="http://www.zhangjunbk.com">张军个人网站</a> <a target=_blank href="http://user.qzone.qq.com/360901061/">张军QQ空间</a>} */ public class DBFUtil implements Serializable { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(DBFUtil.class); // str = Md5Util.toMd5("zhangjundbf201611040930"); // System.out.println(str); // str = Md5Util.toMd5("zhangjundbf201611040931"); // System.out.println(str); /** * 读取DBF数据 * * @param path * dbf文件路径 * @author 张军 * @date 2015-11-03 21:59:00 * @modifiyNote * @version 1.0 * @return */ public static void readDBF(DBFRead p_read) { // 清空值 p_read.reset(); InputStream fis = null; try { // 读取文件的输入流 fis = new FileInputStream(p_read.paramPath); // 根据输入流初始化一个DBFReader实例,用来读取DBF文件信息 p_read.rtnReader = new DBFReader(fis, p_read.paramCharset); // 调用DBFReader对实例方法得到path文件行数,包含删除和隐藏的行 p_read.rtnRecordsCount = p_read.rtnReader.getRecordCount(); // 调用DBFReader对实例方法得到path文件中字段的个数 p_read.rtnFieldsCount = p_read.rtnReader.getFieldCount(); // 取出字段信息 for (int i = 0; i < p_read.rtnFieldsCount; i++) { // 获取DBF字段信息 DBFField field = p_read.rtnReader.getField(i); p_read.rtnFields.add(field); // 转换为大写 String fieldName = JavaUtil.toUpperCase(JavaUtil.trim(field.getName())); p_read.rtnFieldNames.add(fieldName); } Object[] rowValue = null; // 一条条取出path文件中记录 while ((rowValue = p_read.rtnReader.nextRecord()) != null) { // 取出字段信息 p_read.rtnCheckColFieldValue.clear(); for (int i = 0; i < p_read.rtnFieldsCount; i++) { // 获取DBF字段信息 DBFField field = p_read.rtnReader.getField(i); String fieldName = JavaUtil.toUpperCase(JavaUtil.trim(field.getName())); Object fieldValue = rowValue[i]; p_read.rtnCheckColFieldValue.put(fieldName, fieldValue); } // 用此rtnCheckColFieldValue键值进行判断 int checkRow = p_read.checkRow(); if (p_read.BREAK == checkRow) { break; } if (p_read.CONTINUE == checkRow) { continue; } if (p_read.OK != checkRow) { throw new ServiceException("返回值只支持[OK、CONTINUE、BREAK]"); } // 实例化一行行值 Map<String, Object> rowValues = new HashMap<String, Object>(); // 添加一行记录值 p_read.rtnRowFieldValues.add(rowValues); p_read.rtnRowValues.add(rowValue); // 取出字段信息 for (int i = 0; i < p_read.rtnFieldsCount; i++) { // 获取DBF字段信息 DBFField field = p_read.rtnReader.getField(i); String fieldName = JavaUtil.toUpperCase(JavaUtil.trim(field.getName())); Object fieldValue = rowValue[i]; // // 转换值Double->String // if (fieldValue instanceof Double) { // java.text.DecimalFormat df = new java.text.DecimalFormat(); // df.setGroupingUsed(false); // fieldValue = df.format(fieldValue); // } // 添加一行行值 rowValues.put(fieldName, fieldValue); // 添加对应的键值数据 List<Object> values = p_read.rtnColFieldValues.get(fieldName); if (values == null) { values = new ArrayList<Object>(); p_read.rtnColFieldValues.put(fieldName, values); } // 添加值 values.add(fieldValue); // System.out.print(fieldName + ":" + fieldValue + "\t"); } // System.out.println(); } } catch (Exception e) { throw new ServiceException(e); } finally { try { fis.close(); } catch (Exception e) { } } } /** * 通用写dbf文件 * * @param p_path * DBF文件路径 * @param p_fields * 字段值,下面4个字段必须填写 * @see {@link com.linuxense.javadbf.DBFField#setFieldLength(int)}; * @see {@link com.linuxense.javadbf.DBFField#setDecimalCount(int)}}; * @see {@link com.linuxense.javadbf.DBFField#setName(String)}; * @see {@link com.linuxense.javadbf.DBFField#setDataType(byte)}; * @see byte:{@link com.linuxense.javadbf.DBFDataType#类型}(byte code, int minSize, int maxSize, int defaultSize, boolean writeSupported) * @see byte:{@link com.linuxense.javadbf.DBFDataType#CHARACTER}('C', 1, 254, 0, true) * @see byte:{@link com.linuxense.javadbf.DBFDataType#DATE}('D', 8, 8, 8, true) * @see byte:{@link com.linuxense.javadbf.DBFDataType#FLOATING_POINT}('F', 1, 20, 0, true) * @see byte:{@link com.linuxense.javadbf.DBFDataType#LOGICAL}('L', 1, 1, 1, true) * @see byte:{@link com.linuxense.javadbf.DBFDataType#NUMERIC}('N', 1, 32, 0, true) * * @param p_rowValues * 行值 */ public static void writeDBF(DBFWrite p_write) { OutputStream fos = null; try { if (CheckUtil.isNull(p_write.paramPath)) { throw new ServiceException("paramPath:文件路径不能为空"); } // 创建文件对应的上级目录 File v_pfile = new File(FileUtil.getParentPath(p_write.paramPath)); if (!v_pfile.exists()) { v_pfile.mkdirs(); } if (p_write.paramRead != null) { // 自动赋值 p_write.paramFields = p_write.paramRead.rtnFields; p_write.paramRowValues = p_write.paramRead.rtnRowValues; } // 定义DBF文件字段 int v_columnSize = p_write.paramFields.size(); // 转换为list好操作 List<DBFField> v_fieldList = new ArrayList<DBFField>(); // 添加列 for (int i = 0; i < v_columnSize; i++) { try { DBFField r_field = p_write.callbackResetField(p_write.paramFields.get(i)); if (r_field == null) { continue; } v_fieldList.add(r_field); } catch (Exception e) { // 异常退出 logger.error("设置字段异常,中断循环", e); break; } } // 最终的字段 v_fieldList = p_write.callbackResetFields(v_fieldList); DBFField[] v_fields = JavaUtil.listToArray(v_fieldList, DBFField.class); // 定义DBFWriter实例用来写DBF文件 // 定义输出流,并关联的一个文件 fos = new BufferedOutputStream(new FileOutputStream(p_write.paramPath)); DBFWriter writer = new DBFWriter(fos, p_write.paramCharset); // 把字段信息写入DBFWriter实例,即定义表结构 writer.setFields(v_fields); for (Object[] v_rowValue : p_write.paramRowValues) { try { List<Object> p_rowValue = Arrays.asList(v_rowValue); // 不执行下面方法,则报:java.lang.UnsupportedOperationException p_rowValue = new ArrayList<Object>(p_rowValue); // System.out.println("old:" + p_rowValue.size()); // 如果不想改变p_rowValue值,则使用JavaUtil.deepCopy(p_rowValue)深度拷贝list List<Object> r_rowValue = p_write.callbackResetRowValue(v_fieldList, p_rowValue); if (r_rowValue == null) { continue; } // System.out.println("new:" + p_rowValue.size()); writer.addRecord(JavaUtil.listToArray(r_rowValue, Object.class)); } catch (Exception e) { // 异常退出 logger.error("设置值异常,中断循环", e); break; } } // 写入数据 writer.close(); } catch (Exception e) { throw new ServiceException(e); } finally { try { fos.close(); } catch (Exception e) { } } } /** * 导出DBF文件 * * @param p_titles * 标题,格式为,名称|类型|长度|精度 * @param p_listValues * 值 * @param dbfFile * DBF文件 */ public static void exportDBF(List<String> p_titles, List<Object[]> p_listValues, File dbfFile) { exportDBF(null, p_titles, p_listValues, dbfFile); } /** * 导出DBF文件 * * @param write * DBF写入对象 * @param p_titles * 标题,格式为,名称|类型|长度|精度 * @param p_listValues * 值 * @param dbfFile * DBF文件 */ public static void exportDBF(DBFWrite write, List<String> p_titles, List<Object[]> p_listValues, File dbfFile) { if (write == null) write = new DBFWrite(); for (String v_title : p_titles) { String[] v_titleAry = JavaUtil.split(v_title, "|"); String name = ""; // 默认字符 char type = 'C'; // 默认长度为100 int length = 0; int decimalCount = 0; if (v_titleAry.length == 1) { // 默认字符 name = v_titleAry[0]; } else if (v_titleAry.length == 2) { name = v_titleAry[0]; type = JavaUtil.toUpperCase(v_titleAry[1]).toCharArray()[0]; } else if (v_titleAry.length == 3) { name = v_titleAry[0]; type = JavaUtil.toUpperCase(v_titleAry[1]).toCharArray()[0]; length = TypeUtil.Primitive.intValue(v_titleAry[2]); } else if (v_titleAry.length == 4) { name = v_titleAry[0]; type = JavaUtil.toUpperCase(v_titleAry[1]).toCharArray()[0]; length = TypeUtil.Primitive.intValue(v_titleAry[2]); decimalCount = TypeUtil.Primitive.intValue(v_titleAry[3]); } // System.out.println(name + "," + type + "," + length + "," + decimalCount); if (length == 0) { // 一般由自己根据情况定义 length = write.defaultSize; } write.paramFields.add(new DBFField(name, DBFDataType.fromCode(type), length, decimalCount)); } // List<Map<String, Object>> v_listMap = queryResult.rtnDatas; // System.out.println(v_listMap); // for (Map<String, Object> v_map : v_listMap) { // System.out.println(v_map); // } // System.out.println(p_listValues); // for (Object[] v_listValue : p_listValues) { // System.out.println(Arrays.toString(v_listValue)); // } write.paramRowValues = p_listValues; write.paramPath = dbfFile; writeDBF(write); } }
本文为张军原创文章,转载无需和我联系,但请注明来自张军的军军小站,个人博客http://www.zhangjunbk.com