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