亲测可用,也是为了帮助更多需要的人。
java解析DBF文件并保存到数据库
首先我们来说说,解析文件需要那几个步骤
1.先将文件进行上传,上传至指定路径。
2.获取上传至指定路径的文件,进行解析。
直接上代码吧
首先我们上传文件使用commons-io的依赖包
导入依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>com.github.albfernandez</groupId>
<artifactId>javadbf</artifactId>
<version>1.13.1</version>
</dependency>
编写文件上传工具类
package com.infoearth.modules.area.utils;
import org.apache.commons.io.FileUtils;
import org.springblade.core.tool.api.R;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
public class UploadFileUtil {
public R uploadImoprtFile(MultipartFile multipartFile,String filePath) {
if (null != multipartFile) {
try {
File sourcePath = new File(filePath);
if (!sourcePath.exists()) {
sourcePath.mkdirs();
}
String filename = multipartFile.getOriginalFilename();
String filenamePath = filePath + filename.substring(0, filename.lastIndexOf("."))
+ "_"
+ System.currentTimeMillis()
+ filename.substring(filename.lastIndexOf("."));
File thisFile = new File(filenamePath);
FileUtils.writeByteArrayToFile(thisFile, multipartFile.getBytes());
//返回新文件的路径
return R.data(filenamePath);
} catch (IOException e) {
e.printStackTrace();
return R.fail("操作失败");
}
}
return R.fail("操作失败");
}
}
ServiceImpl层
获取上传的文件并解析
public boolean checkDbfFile(MultipartFile multipartFile) {
UploadFileUtil uploadFileUtil = new UploadFileUtil();
R r = uploadFileUtil.uploadImoprtFile(multipartFile,baseFilePath);
//获取上传文件的路径
String filePath = r.getData().toString();
try {
DBFReader dbfReader = new DBFReader(new FileInputStream(filePath));
//解决乱码
dbfReader.setCharactersetName("GBK");
//读取文件中字段的个数
int fieldCount = dbfReader.getFieldCount();
String[] fieldName = new String[fieldCount];
for (int i = 1; i < fieldName.length; i++) {
String name = dbfReader.getField(i).getName();
if(!name.equals("ALF") && !name.equals("AREA")){
return false;
}
}
Object[] rowValues;
while ((rowValues=dbfReader.nextRecord())!=null){
Map<String,String> rowMap = new HashMap<>();
for (int i = 0; i < rowValues.length; i++) {
rowMap.put(dbfReader.getField(i).getName(), String.valueOf(rowValues[i]).trim());
}
//将解析后的数据加入数据表
EvalParamTab evalParamTab = new EvalParamTab();
evalParamTab.setId(GetUUID.getUUID());
evalParamTab.setAlf(rowMap.get("ALF"));
evalParamTab.setArea(rowMap.get("AREA"));
baseMapper.insert(evalParamTab);
}
dbfReader.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
}
controller层
/**
* DBF文件上传
*/
@PostMapping("/dbfUploadFile")
@ApiOperation(value = "DBF文件上传",notes ="userName tskName 必传" )
public R dbfUploadFile(@RequestParam(name = "file") MultipartFile multipartFile){
boolean flag = evalParamTabService.checkDbfFile(multipartFile);
if(flag){
return R.success("上传成功");
}
return R.fail("上传失败,请检查文件格式或者表头");
}
就此结束,希望能帮到各位小伙伴。