Dbf文件操作

package cn.com.szhtkj.util;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.NamingException;

import org.apache.commons.beanutils.PropertyUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.linuxense.javadbf.DBFField;
import com.linuxense.javadbf.DBFWriter;

import cn.com.szhtkj.dto.SjxmDtoOutput;




public class ExportDbf {
    private static final String CHARSET = "GBK";
//  private static File dataFile;
    private final static int records =  2000;   
    /**
     * 写入文件
     * @param beans
     * @param propertys
     * @return
     * @throws DocumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     * @throws IOException
     */
    public static String writeDbf(List<?> beans, String templateName,String dbfName) throws DocumentException,
        IllegalAccessException, InvocationTargetException, NoSuchMethodException,
        IOException {
        try {
        List<?> propertys = readTemplate(templateName);
        DBFWriter writer = new DBFWriter(new File(dbfName));
        writer.setCharactersetName(CHARSET);
        writer.setFields(writeFields(propertys));
        for (int i = 0; i < beans.size(); i++) {
            writer.addRecord(writeLine(beans.get(i), propertys));
        }
        writer.write();   
        return "succ";
    } catch (Exception e) {
        e.printStackTrace();
         return "error";
    }
}
    /**
     * 写入文件
     * @param beans
     * @param propertys
     * @return 第一次写入dbf已经写入dbf表结构,所以不需要二次写入
     * @throws DocumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     * @throws IOException
     */
    public static String writeDbf2(List<?> beans, String templateName,String dbfName) throws DocumentException,
        IllegalAccessException, InvocationTargetException, NoSuchMethodException,
        IOException {
        try {
        List<?> propertys = readTemplate(templateName);
        DBFWriter writer = new DBFWriter(new File(dbfName));
        writer.setCharactersetName(CHARSET);
        writer.setFields(writeFields(propertys));
        for (int i = 0; i < beans.size(); i++) {
            writer.addRecord(writeLine(beans.get(i), propertys));
        }
        writer.write();   
        return "succ";
    } catch (Exception e) {
        e.printStackTrace();
         return "error";
    }
}
    /**
     * 读取配置文件
     * @param filename
     * @return
     * @throws DocumentException
     */
    private static List<?> readTemplate(String filename) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(filename);
        return document.getRootElement().elements();
    }
    /**
     * 解析dbf文件
     * @param clazz
     * @param propertys
     * @param values
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     */
    @SuppressWarnings("unused")
    private static Object readLine(Class<?> clazz, List<?> propertys, Object[] values)
        throws InstantiationException, IllegalAccessException, InvocationTargetException,
        NoSuchMethodException {
        Object bean = clazz.newInstance();
        for (int i = 0; i < propertys.size(); i++) {
            Element property = (Element) propertys.get(i);
            Object value = values[i];
            if (property.attributeValue("type").equals("C")) {
                value = ((String) value).trim();
            }
            PropertyUtils.setProperty(bean, property.attributeValue("name"), value);
        }
        return bean;
    }
    /**
     * 返回每行匹配配置xml的数�?
     * @param bean
     * @param propertys
     * @return
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     */
    private static Object[] writeLine(Object bean, List<?> propertys)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        Object[] row = new Object[propertys.size()];
        for (int i = 0; i < propertys.size(); i++) {
            Element element = (Element) propertys.get(i);
            row[i] = PropertyUtils.getProperty(bean, element.attributeValue("name"));
        }
        return row;
    }
    /**
     * 设置写入dbf文件字段类型
     * @param propertys
     * @return
     */
    private static DBFField[] writeFields(List<?> propertys) {
        DBFField[] fields = new DBFField[propertys.size()];
        for (int i = 0; i < propertys.size(); i++) {
            Element property = (Element) propertys.get(i);
            fields[i] = new DBFField();
            fields[i].setName(property.attributeValue("column"));
            fields[i].setDataType((byte) property.attributeValue("type").charAt(0));
            if (property.attributeValue("length") != null) {
                fields[i].setFieldLength(Integer.parseInt(property.attributeValue("length")));
            }
            if (property.attributeValue("scale") != null) {
                fields[i].setDecimalCount(Integer.parseInt(property.attributeValue("scale")));
            }
        }
        return fields;
    }
    /**
     * 启动程序方法
     * @throws NamingException 
     * @throws SQLException 
     * @throws IOException 
     * @throws NoSuchMethodException 
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
     * @throws DocumentException 
     */
    @SuppressWarnings("static-access")
    public static int setUp(String fcode, String xmlNameAndPath, List<SjxmDtoOutput> list) throws SQLException, NamingException, DocumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException {
        File file = new File(fcode);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        if(file.exists()){
            deleteFile(fcode);
        }
        String succ="";
         ExportDbf ep=new ExportDbf();
         //取得总记录数,进行分页处理    
            long  count = list.size(); 
            if(count >0){
                long  page = count / records;   
                if  (count % records !=  0 ) {   
                    page = page + 1 ;   
                }   
                //开始行号,结束行号    
                long start =  1 , end = records;     
                //根据页数进行循环    
                List<SjxmDtoOutput> orders = new ArrayList<SjxmDtoOutput>();
                for  ( long  j =  1 ; j <= page; j++) { 
                 if(list.size() > 0){
                      for(int i=0;i<list.size();i++){
                         SjxmDtoOutput order = new SjxmDtoOutput();
                         order.setBmbh(list.get(i).getBmbh());
                         order.setBmmc(list.get(i).getBmmc()+"                 ");
                         order.setSjxmdm(list.get(i).getSjxmdm());
                         order.setXmbh(list.get(i).getXmbh());
                         order.setXmmc(list.get(i).getXmmc()+"                 ");
                         orders.add(order);
                     }
                    //调用生成dbf方法
                      if(j >1){
                          succ=ep.writeDbf2(orders, xmlNameAndPath,fcode);
                          orders.clear();
                      }else{
                          succ=ep.writeDbf(orders, xmlNameAndPath,fcode);
                          orders.clear();
                      }
                  }
                 start = end + 1 ;   
                 end = end + records;
             }
            }
            if(count == 0){
                return 99;
            }else if(succ.equals("succ")){
                return 88;
            }else{
                return 66;
            }
            
    }

    /**
     * 
     * 删除
     * @param sPath
     * @return
     */
    public static boolean deleteFile(String sPath) {  
        Boolean flag = false;  
        File file = new File(sPath);  
        // 路径为文件且不为空则进行删除  
        if (file.isFile() && file.exists()) {  
            file.delete();  
            flag = true;  
        }  
        return flag;  
    }  
     public static void main(String[] args) throws Exception {
//       ExportDbf dbf=new ExportDbf();
//       File xing=new File(System.getProperty("user.dir"));
//       String x=xing.getPath().replace("\\", "\\\\");
//       String cs1=x+"\\export.dbf";
//       System.out.println(cs1);
//       setUp(cs1);
      }
     

}

转载于:https://www.cnblogs.com/sunBinary/p/10955377.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
javadbf-0.4.0版本本已增加setCharactersetName方法支持中文读写,但在写入时会发生写入中文数据丢失问题。资源压缩文件包含有修改后的jar文件和读写测试类。 @Test public void testWrite1(){ File file=new File(this.folder, "测试数据.DBF"); OutputStream fos = null; try { // 定义DBF文件字段 DBFField[] fields = new DBFField[3]; // 分别定义各个字段信息,setFieldName和setName作用相同, // 只是setFieldName已经不建议使用 fields[0] = new DBFField(); // fields[0].setFieldName("emp_code"); fields[0].setName("semp_code"); fields[0].setDataType(DBFField.FIELD_TYPE_C); fields[0].setFieldLength(10); fields[1] = new DBFField(); // fields[1].setFieldName("emp_name"); fields[1].setName("emp_name"); fields[1].setDataType(DBFField.FIELD_TYPE_C); fields[1].setFieldLength(200); fields[2] = new DBFField(); // fields[2].setFieldName("salary"); fields[2].setName("salary"); fields[2].setDataType(DBFField.FIELD_TYPE_N); fields[2].setFieldLength(12); fields[2].setDecimalCount(2); // DBFWriter writer = new DBFWriter(new File(path)); // 定义DBFWriter实例用来写DBF文件 DBFWriter writer = new DBFWriter(); writer.setCharactersetName("GBK"); // 把字段信息写入DBFWriter实例,即定义表结构 writer.setFields(fields); // 一条条的写入记录 Object[] rowData = new Object[3]; rowData[0] = "1000234567"; // "中文";// -42 -48 -50 -60 rowData[1] = "中文"; rowData[2] = new Double(5000.00); writer.addRecord(rowData); rowData = new Object[3]; rowData[0] = "1001"; rowData[1] = "Lalit"; rowData[2] = new Double(3400.00); writer.addRecord(rowData); rowData = new Object[3]; rowData[0] = "1002"; rowData[1] = "Rohit"; rowData[2] = new Double(7350.00); writer.addRecord(rowData); // 定义输出流,并关联的一个文件 fos = new FileOutputStream(file); // 写入数据 /* * 注意:writer.addRecord(rowData)时并不真正写入数据,在最后writer.write(fos)时才会把数据写入DBF文件,之前addRecord的数据暂时存放在内存中。如果数据量过大,这种方式显然不适合. */ writer.write(fos); } catch (Exception e) { e.printStackTrace(); } finally { try { fos.close(); } catch (Exception e) { } } } /** * JavaDBF提供的另外一种机制:Sync Mode(同步模式)解决数据量过大这个问题 */ @Test public void testWrite2(){ File file=new File(this.folder, "测试数据.DBF"); DBFWriter writer = null; try { if(file.exists()){ file.delete(); } // 定义DBF文件字段 DBFField[] fields = new DBFField[3]; // 分别定义各个字段信息,setFieldName和setName作用相同, // 只是setFieldName已经不建议使用 fields[0] = new DBFField(); // fields[0].setFieldName("emp_code"); fields[0].setName("semp_code"); fields[0].setDataType(DBFField.FIELD_TYPE_C); fields[0].setFieldLength(10); fields[1] = new DBFField(); // fields[1].setFieldName("emp_name"); fields[1].setName("emp_name"); fields[1].setDataType(DBFField.FIELD_TYPE_C); fields[1].setFieldLength(200); fields[2] = new DBFField(); // fields[2].setFieldName("salary"); fields[2].setName("salary"); fields[2].setDataType(DBFField.FIELD_TYPE_N); fields[2].setFieldLength(12); fields[2].setDecimalCount(2); // DBFWriter writer = new DBFWriter(new File(path)); // 定义DBFWriter实例用来写DBF文件 writer = new DBFWriter(file); writer.setCharactersetName("GBK"); // 把字段信息写入DBFWriter实例,即定义表结构 writer.setFields(fields); // 一条条的写入记录 Object[] rowData = new Object[3]; rowData[0] = "1000234567"; rowData[1] = "中文1"; rowData[2] = new Double(5000.00); writer.addRecord(rowData); rowData = new Object[3]; rowData[0] = "1001"; rowData[1] = "Lalit"; rowData[2] = new Double(3400.00); writer.addRecord(rowData); rowData = new Object[3]; rowData[0] = "1002"; rowData[1] = "Rohit"; rowData[2] = new Double(7350.00); writer.addRecord(rowData); } catch (Exception e) { e.printStackTrace(); } finally { if(writer!=null){ try { writer.write(); } catch (Exception e) {} } } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值