互联网金融项目——工作日志(六)玩转文件读取

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/successA/article/details/53240438

  换了新工作,博客停了几个星期,重新开始坚持码博客~不总结,就像出门不穿衣服,别扭的不行。

  最近花两周做的一个项目,主要是对第三方发送过来的核心数据进行合并、校验、加密、压缩、生成明文,密文的过程。

  传送数据采用的文件开始使用.xlsx格式,特点就是3个月数据,按月拆分,多个sheet,数据量大,采用POI的操作模式。windows  系统6g的内存,依然会被跑爆。

  后来应我方需求,按天拆分,分成3种格式的报文,给我们的格式变成了.cvs,后来又变成了.txt。


为什么要进行格式的改变?


  首先介绍一下这三种文件格式的特征。

  .xlsx: excel文件扩展名,基于新的xml文件压缩格式,包含book,sheet,cell等单元,可以通过POI直接进行office文档操作。

  .csv:  逗号分隔值(Comma-Separated Values),文件以纯文本形式存储表格数据。比如用txt文件打开,就是一行一条记录,以逗号分割。

  .txt:  文本格式,存储文本信息,体积小,存储简单,格式通用,不会中毒。

       从特殊到普通是创造。为了能试用于更多的文件格式,我们采用了最最基础的.txt文件,这样可以把这三种格式的文件,都转换成文本文件,以逗号分割,记录数据信息的形式。进行读取,逐行解析和组装,一站式的操作,可以应对更多的变化。


通过IO读取文件,合并  

    /**
	 * 读取文件所有行信息
	 * @param fileName 文件路径名称 例如:D:\\CreateFile\\20160705_1_123.txt;
	 * @return 文件内容
	 */
	public  static  List<String> readAllLines(String fileName){
		List<String> cardInfoList=new ArrayList<String>();
		try {
			@Cleanup
			BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), StandardCharsets.UTF_8));//换成你的文件名
			String line = null;
			while((line=reader.readLine())!=null){
				cardInfoList.add(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cardInfoList;

	}


	public  static  void writeAllLines(String fileName, List<String> listLines){
		if(listLines == null || listLines.size() == 0)
			return ;

		try {
			@Cleanup
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), StandardCharsets.UTF_8));//换成你的文件名
			int count = 0;
			for (String line:listLines)
			{
				if(line != null)
				{
					writer.write(line);
					count ++;
					if(count != listLines.size())
						writer.write("\r\n");
				}
			}

			writer.flush();
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}




获取.txt为后缀的所有文件,获取整个文件名(含路径) / 获取文件名(不含路径)

        String plainFilePath = "D:\\job\\codeSource\\data\\plain\\";
        File file = new File(plainFilePath);
        File[] tempList = file.listFiles();
        List<String> listFile = new ArrayList<String>();
        String fileName ;
        for (int i = 0; i < tempList.length; i++) {
            fileName = tempList[i].toString();
            if(!fileName.substring(fileName.length() - 3).equals("txt"))//获取后缀为.txt为后缀的所有文件
                continue;
            listFile.add(tempList[i].toString());
        }

   String holeFilePath ;
   String partFilePath ;
   CreditMessage message = new CreditMessage();
   //读取明文内容,并解析成message
   for (int j = 0; j < listFile.size(); j++) {
     holeFilePath = listFile.get(j);//获取整个文件路径+文件名
     partFilePath = holeFilePath.substring(holeFilePath.lastIndexOf("\\") + 1, holeFilePath.lastIndexOf("."));//获取文件名
   }


   


Byte数组的截取

 /**
     * 获取头string字符串
     * @param Length  截取长度
     * @param start 截取初始位置
     * @param end  截取终止位置
     * @param creditMessageHead 截取字符串
     * @return 截取字符串
     */
    private static String getMessageHeadMessge(int Length, int start, int end, byte[] creditMessageHead){
        byte[] strDataVersion=new byte[Length];
        for(int i =start;i<end;i++){
            strDataVersion[i-start]=creditMessageHead[i];
        }
        String str=null;
        try{
             str=new String (strDataVersion,"GB18030").trim();
        }catch (Exception e){
            e.printStackTrace();
        }
        return  str ;
    }



枚举的使用

//枚举定义
@Getter
public enum ItemIdentityEnum {
    CREDIT_AMOUNT("9100", "授信额度", DataType.N, 10, true),
    SHARE_CREDIT_AMOUNT("9101", "共享授信额度", DataType.N, 10, true),
   
    //标识符
    private String   code;
    //数据项名称
    private String   name;
    //类型
    private DataType type;
    //长度
    private int      length;
    //是否必填
    private boolean  required;

    ItemIdentityEnum(String code, String name, DataType type, int length, boolean required) {
        this.code = code;
        this.name = name;
        this.type = type;
        this.length = length;
        this.required = required;
    }
}

//枚举取值

ItemIdentityEnum.CREDIT_AMOUNT.getLengt();

//枚举赋值
public CreditMessageBaseSegment setBusinessCategory(BusinessCategoryEnum value) {
  businessCategory.setValue(value);
  return this;
}




异常的使用

  public static void writeLogFile(Exception e,String businessNo){
            try{
                FileWriter fileWriter=null;
                //创建文件的输出流
                fileWriter=new FileWriter("D:\\error\\error.txt",true);
                fileWriter.write("\r\n"+e+"\r\n"+"业务号:"+businessNo+"\r\n");
                fileWriter.close();
            }
            catch(Exception s){
                s.printStackTrace();
            }
        }


   项目比较小,用时2周,最终达到的效果是,能读取各种类型文件,校验过程中无需叫停,一站记录所有错误日志,明文生成、校验、压缩解耦合,避免了操作之间的干扰。

  这是新公司的第一个入手项目,运行结果,很让人激动兴奋,很开心能跟如此优秀的人一起共事,进步。感恩所经历的一切人和事~




  


猜你喜欢

转载自blog.csdn.net/successA/article/details/53240438