Java读取dbf文件, 并将内容插入到数据库(数据库操作见“jdbc批量插入一文”)。用当前博客中的代码读取中文会乱码。 用博客最下面提供的资源链接可以解决中文乱码问题
需要使用到javadbf.jar 文件, 最下面的资源链接中指向的资源,包含该jar
maven仓库配置为:
<dependency>
<groupId>com.linuxense</groupId>
<artifactId>javadbf</artifactId>
<version>0.4.0</version>
</dependency>
package com.thinkive.common.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import com.linuxense.javadbf.DBFReader;
import com.thinkive.common.function.gastatisics.bean.Bean;
/**
* @desc:读取dbf文件,并将内容插入到数据库
* @author: changez@thinkive.com
* @time: 2016年11月28日 下午3:37:50
*/
public class ReadDBF {
private static Logger logger = Logger.getLogger(ReadDBF.class);
// path:bdf文件路径, ignoreRows:要忽略的行数,如第一行标题行, 默认读取的时候会忽略第一行,需要测试确定。
public static void readDbfAndInstallDB(String path, int ignoreRows) throws Exception {
if(path == null || "".equals(path) || !path.endsWith("dbf")) {
logger.error("该dbf文件不存在: "+path);
return ;
}
File file = new File(path);
if(!file.exists()) {
logger.error("该dbf文件不存在: "+path);
return ;
}
List<Bean> beanList = new ArrayList<Bean>();
InputStream fis = null;
DBFReader reader = null;
try {
fis = new FileInputStream(file);
// 读取DBF文件信息
reader = new DBFReader(fis);
//存放当前行中的值
Object[] rowValues = null;
int result = 1; // 用来计数已经准备好的 待处理数据数量
//忽略行数
if(ignoreRows > 0) {
for (int i = 0; i < ignoreRows; i++) {
rowValues = reader.nextRecord();
}
}
while ((rowValues = reader.nextRecord()) != null) {
// System.out.println(++result+" "+rowValues[0]+","+rowValues[1]+","+rowValues[2]+","+rowValues[3]);
Bean bean = new Bean((rowValues[0]+"").trim(),(rowValues[1]+"").trim(), (rowValues[2]+"").trim(), (rowValues[3]+"").trim(), Constants.CHANNEL_TYPE_ZHONG_DENG);
beanList.add(bean);
if(++result%Constants.BATCH_NUM == 0) {
// 数据库操作见“jdbc批量插入一文”
DBHelp.executeUpate(DBHelp.SQL_INSTALL_IDNO_THIRD, beanList, Constants.DATE_FORMATE_DEFAULT);
beanList.clear();
}
}
if(beanList.size() > 0) {
DBHelp.executeUpate(DBHelp.SQL_INSTALL_IDNO_THIRD, beanList, Constants.DATE_FORMATE_DEFAULT);
}
DBHelp.closeSources(DBHelp.getConn(), DBHelp.getPs());
beanList.clear();
beanList = null;
} finally {
try {
if(fis != null) {
fis.close();
}
} catch (Exception e) {
logger.error("流关闭失败" , e);
}
}
}
}
//===>
这里有一篇博客,详细的写了如何解决乱码的问题。 博客中贴出来了所有的代码,以及读, 写, 插入数据库等代码实现。 为了方便我将代码复制出来搞成了一个Java工程。
原博客地址: http://www.xuebuyuan.com/2097548.html
Java工程资源地址:http://download.csdn.net/detail/changerzhuo_319/9724413