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: [email protected]
* @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