java操作txt文件,取值-转实体-并保存到数据库

来源:互联网 发布:淘宝直播怎么弄 编辑:程序博客网 时间:2024/06/09 21:09

java操作txt文件,取值-转实体-并保存到数据库

完整的ssh代码请查看 https://github.com/Bestcxy/SSH-ajax-axis2-maven-log4j-redis

如果你还没有加入github 请先阅读 http://blog.csdn.net/bestcxx/article/details/63687217


txt文件为 filetxt.txt,内容为

标题:测试txt文件
编号 价格 日期  名称
0001 1.01 20170323010101 苹果
0002 10.01 20170323010101 桃子


位于   WEB-INF/file/filetxt.txt,路径要注意使用了枚举,应用的话直接改为字符串



package com.bestcxx.mavenstu.mavenssh.file;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.math.BigDecimal;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.springframework.beans.factory.annotation.Autowired;import com.bestcxx.mavenstu.mavenssh.model.FileTxtModel;import com.bestcxx.mavenstu.mavenssh.service.FileTxtModelService;import com.bestcxx.mavenstu.mavenssh.util.DateUtil;import com.bestcxx.mavenstu.mavenssh.util.EnumUtil;/** *  * @theme 对txt文件进行按行、列操作 * @author wujie * @Datetime 2017年3月23日 上午10:26:12 */public class FileTxt {private static Logger logger = LogManager.getLogger(FileTxt.class);@Autowiredprivate FileTxtModelService fileTxtModelService;public FileTxt(){}public FileTxt(FileTxtModelService fileTxtModelService){this.fileTxtModelService=fileTxtModelService;}String filePath = EnumUtil.FILE_TXT_PATH.toString();// 文本路径 src/main/webapp/WEB-INF/file/filetxt.txtString encoding = EnumUtil.COMMON_ENCODING.toString();// 编码格式public void ReadFileTxt() {File txtFile = new File(filePath);// 读取文件InputStream in = null;InputStreamReader read = null;BufferedReader reader = null;try {in = new FileInputStream(txtFile);read = new InputStreamReader(in, encoding);// 构建文件缓存reader = new BufferedReader(read);String temLine = "";// 每一行的内容// 默认输出前两行logger.info("第一行:" + reader.readLine());logger.info("第二行:" + reader.readLine());// 循环遍历txt文件while ((temLine = reader.readLine()) != null) {String[] split = temLine.split("\\s");// 以多个空格作为分隔符for (String tem : split) {logger.info(tem);}FileTxtModel fileTxtModel = new FileTxtModel();fileTxtModel.setIdentifier(split[0]);fileTxtModel.setPrice(new BigDecimal(split[1]));fileTxtModel.setDateTime(DateUtil.getDateFromStr_yyyyMMddHHmmss(split[2]));fileTxtModel.setName(split[3]);fileTxtModelService.add(fileTxtModel);}} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocklogger.error(e.toString());} catch (FileNotFoundException e) {// TODO Auto-generated catch blocklogger.error(e.toString());} catch (IOException e) {// TODO Auto-generated catch blocklogger.error(e.toString());} finally {try {if (in != null) {in.close();}if (read != null) {read.close();}if (reader != null) {reader.close();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}


txt的写入操作  http://blog.csdn.net/bestcxx/article/details/51381460


0 0