springBoot代码结构:
所需pom依赖
数据库表设计
话不多说,先放代码:MeteorologicalService
public void testReadByDoc(String path) throws Exception {
Meteorological meteorological = new Meteorological();
String [] content =null;
//取当前.字段的下标
int i = path.indexOf(".");
//把文件读取到流
InputStream is = new FileInputStream(path);
if(path.length()-i==4){ //doc文件
HWPFDocument doc = new HWPFDocument(is);
Range range = doc.getRange();
//读取word 转化为段落格式
content =MeteorologicalUtil.printInfo(range);
}else { // docx 文件
XWPFDocument xdoc = new XWPFDocument(is);
content =MeteorologicalUtil.printInfox(xdoc);
}
//去掉空的段落
String[] contenta = MeteorologicalUtil.removeArrayEmptyTextBackNewArray(content);
//取数组长度
int len =contenta.length;
Date time = MeteorologicalUtil.getTime(contenta); //获得天气预报的时间
String s = contenta[len - 6];
if(s.contains("和")){ //判断是否包含和
meteorological.setAlert(contenta[len-5]);
meteorological.setWeather(contenta[len-4]);
}
String minimum = contenta[len - 1].substring(0, contenta[len - 1].length() - 1);
String maximum = contenta[len - 2].substring(0, contenta[len - 2].length() - 1);
String windforce = contenta[len - 3].substring(0, contenta[len - 3].length() - 1);
meteorological.setWeather(contenta[len-4]);
meteorological.setMaximum(maximum);
meteorological.setMinimum(minimum);
meteorological.setNowtime(time);
meteorological.setWindforce(windforce);
meteorologicalMapper.insert(meteorological); //封装、保存
is.close();
}
此段代码步骤:
首先解析word文档,以段落的形式读取文档中内容,此时拿到word文档中信息。
由于文档中可能会出现空格和回车影响我们根据段落处理文档,所以我们此时需要先去掉这些可能会对我们代码产生的影响(部分代码等下贴)
此时去重部分已经解决,这时我们可以根据我们得到的数据进行下一步处理(处理代码也等下贴)
解决完成后将得到的数据放到对象中,然后存到数据库
因为还有定时任务(spring自带的定时器)所以我们需要再加个定时器,好了 话不多说,现在开始贴处理代码。
因为代码问题,所以将一些方法提到了util工具类
public class MeteorologicalUtil {
public static String [] printInfo(Range range) {
//获取段落数
int paraNum = range.numParagraphs();
String [] paragraphArr =new String[paraNum];
for (int i=0; i<paraNum; i++) {
paragraphArr[i] =range.getParagraph(i).text();
}
return paragraphArr;
}
public static String [] printInfox(XWPFDocument xwpfDocument) {
//获取段落数
int paraNum =xwpfDocument.getParagraphs().size();
String [] paragraphArr =new String[paraNum];
List<XWPFParagraph> paragraphs = xwpfDocument.getParagraphs();
for(int i =0 ;i<paraNum;i++){
paragraphArr[i] =paragraphs.get(i).getParagraphText();
}
return paragraphArr;
}
/**
* 获得气象时间
* @param arr
* @return
*/
public static Date getTime(String [] arr){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日HH:mm");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+0")); //消除时差
for (String ph :arr){
String timeStr = patternTime(ph);
if(timeStr!=null){
try {
return simpleDateFormat.parse(timeStr);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
}
return null;
}
/**
* 去掉空的段落
* @param strArray
* @return
*/
public static String[] removeArrayEmptyTextBackNewArray(String[] strArray) {
//将数组转化为list对象
List<String> strList= Arrays.asList(strArray);
List<String> strListNew=new ArrayList<>();
for (int i = 0; i <strList.size(); i++) {
strList.set(i,strList.get(i).replaceAll("\b","").replaceAll("\r",""));
//strList.set(i,strList.get(i).substring(0,strList.get(i).length()-1));
if (strList.get(i)!=null&&!strList.get(i).equals("")){
strListNew.add(strList.get(i)); }
}
//将集合转化为数组
String[] strNewArray = strListNew.toArray(new String[strListNew.size()]);
return strNewArray;
}
public static String patternTime(String content){
//****年**月**日 ****年*月*日 的格式,我们可以更改不同筛选规则,进行不同格式筛选 正则表达式匹配文中时间
Pattern pattern = Pattern.compile("((([0-9]{4})年([0-9]{2}|[1-9]))月([0-9]{2}|[1-9]))日([0-9]{2}|[1-9]):([0-9]{2}|[1-9])"); //尝试提取这样类型的数据
Matcher matcher = pattern.matcher(content);
if (matcher.find()) { //判断文本是否找到符合规则字符串,并提取
String str_ymd = matcher.group(0);
return str_ymd;
}
return null;
}
}
好了,代码已经放上去了,这时候我们就需要加上定时器了(此定时器因为是spring自带的,所以比较简单易懂)
@Configuration //声明是一个配置类
@EnableScheduling //开启定时任务
public class MeteorologicalTask {
@Autowired
MeteorologicalService meteorologicalService;
// @Scheduled(cron = "0 0 1 * * ?") //执行周期(每天凌晨一点执行)(不知道定时时间怎么处理,可以网上看一下 cron)
@Scheduled(cron = "*/5 * * * * ?")//每5秒执行一次
public void work() {
//文件路径
File file = new File("C:\\Users\\qps12\\Desktop\\气象局2");
//获得文件夹下所有文件或者文件夹
File[] fileList = file.listFiles();
for (int i = 0; i < fileList.length; i++) {
if (fileList[i].isFile()) { //只检查文件.并且遍历
File currentFile = fileList[i];
String path = currentFile.getAbsolutePath(); //当前文件的绝对路径
try {
meteorologicalService.testReadByDoc(path); //执行解析、封装、保存数据
} catch (Exception e) {
e.printStackTrace();
return;
}
currentFile.delete(); //删除文件
}
}
}
}
注:此方法只适用于那种格式类型几乎一致的文档处理,如果想处理一些没有规则的文档,最好还是使用模糊匹配的方法(还没研究,所以不会 哈哈),另外贴一下,我自己处理的文档:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。