需求:

定时任务:每天统计昨天的公司支付宝账户实际收益(扣除手续费)

流程:

1 、调用支付宝接口, 获取zip 下载地址

package com.ycmedia.task;

import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.alipay.api.AlipayClient;import com.alipay.api.DefaultAlipayClient;import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest;import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;import com.google.common.base.Splitter;import com.ycmedia.constants.Constants;import com.ycmedia.dao.TaskDao;import com.ycmedia.entity.RealIncom;import com.ycmedia.utils.FileUtil;import com.ycmedia.utils.ReadCsv;

import org.joda.time.DateTime;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.core.env.Environment;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;

import java.io.File;import java.text.SimpleDateFormat;import java.util.Date;import java.util.List;

@Componentpublic class AliBillTask {

    @Autowired    private Environment env;    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    @Autowired    private TaskDao taskDao;

    @Scheduled(cron = "0 14 14 ? * *")    public void runAlitask() throws Exception {        downloadBill();    }

    /**     * 获取指定日期的账单     */    public void downloadBill() throws Exception {        // 将订单提交至支付宝        AlipayClient alipayClient = new DefaultAlipayClient(                "https://openapi.alipay.com/gateway.do", Constants.ALI_APP_ID,                Constants.ALI_PRIVATE_KEY, "json", "utf-8",                Constants.ALI_DEV_PLAT_PUBLIC_KEY);        AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();        JSONObject json = new JSONObject();        json.put("bill_type", "trade");        //昨天的数据        json.put("bill_date", new DateTime().minusDays(1).toString("yyyy-MM-dd"));        request.setBizContent(json.toString());        AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient                .execute(request);        if(response.isSuccess()){            // 获取下载地址url            String url = response.getBillDownloadUrl();            // 设置下载后生成Zip目录            String filePath = env.getProperty("file.path");            String newZip = filePath + new Date().getTime() + ".zip";            // 开始下载            FileUtil.downloadNet(url, newZip);            // 解压到指定目录            FileUtil.unZip(newZip, env.getProperty("file.zip.path"));            // 遍历文件 获取需要的汇整csv            File[] fs = new File(env.getProperty("file.zip.path")).listFiles();            RealIncom income = null;            for (File file : fs) {                if (file.getAbsolutePath().contains("汇总")) {                    Double money = ReadCsv.getMoney("", file.getAbsolutePath());                    income = new RealIncom();                    income.setDate(new Date());                    income.setMoney(money);                    taskDao.insertTodayMoney(income);                }            }            // 插入成功, 删除csv 文件            for (File file : fs) {                file.delete();            }

        }else{            //如果账单不存在, 插入一条空数据到数据库            RealIncom income= new RealIncom();            income.setDate(new Date());            income.setMoney(0.00);            taskDao.insertTodayMoney(income);        }

        if (response.isSuccess()) {            System.out.println("调用成功");        } else {            System.out.println("调用失败");        }        System.out.println(JSON.toJSONString(response));    }

}

工具类代码:

package com.ycmedia.utils;import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;public class FileUtil {/*** 使用GBK编码可以避免压缩中文文件名乱码*/private static final String CHINESE_CHARSET = "GBK";/*** 文件读取缓冲区大小*/private static final int CACHE_SIZE = 1024;/*** 第一步: 把 支付宝生成的账单 下载到本地目录* * @param path*            支付宝资源url* @param filePath*            生成的zip 包目录* @throws MalformedURLException*/public static void downloadNet(String path, String filePath)throws MalformedURLException {// 下载网络文件int bytesum = 0;int byteread = 0;URL url = new URL(path);try {URLConnection conn = url.openConnection();InputStream inStream = conn.getInputStream();FileOutputStream fs = new FileOutputStream(filePath);byte[] buffer = new byte[1204];while ((byteread = inStream.read(buffer)) != -1) {bytesum += byteread;fs.write(buffer, 0, byteread);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public static void unZip(String zipFilePath, String destDir)throws Exception {ZipFile zipFile = new ZipFile(zipFilePath, CHINESE_CHARSET);Enumeration<?> emu = zipFile.getEntries();BufferedInputStream bis;FileOutputStream fos;BufferedOutputStream bos;File file, parentFile;ZipEntry entry;byte[] cache = new byte[CACHE_SIZE];while (emu.hasMoreElements()) {entry = (ZipEntry) emu.nextElement();if (entry.isDirectory()) {new File(destDir + entry.getName()).mkdirs();continue;}bis = new BufferedInputStream(zipFile.getInputStream(entry));file = new File(destDir + entry.getName());parentFile = file.getParentFile();if (parentFile != null && (!parentFile.exists())) {parentFile.mkdirs();}fos = new FileOutputStream(file);bos = new BufferedOutputStream(fos, CACHE_SIZE);int nRead = 0;while ((nRead = bis.read(cache, 0, CACHE_SIZE)) != -1) {fos.write(cache, 0, nRead);}bos.flush();bos.close();fos.close();bis.close();}zipFile.close();}}

目录:

开发环境:

========================================================================================================================

更新实际收益到本地数据库查询

====================更新与2018-11-19 【ReadCsv.java】===================================================

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;public class ReadCsv {// public static void main(String[] args) {// try {//// BufferedReader reader=new BufferedReader(new InputStreamReader(new// FileInputStream("D:\\down\\1476771240197\\20884217298464250156_20160914_业务明细.csv"),"gbk"));// reader.read();//第一行信息,为标题信息,不用,如果需要,注释掉// String line = null;////// while((line=reader.readLine())!=null){// String item[] = line.split("\r\n");//CSV格式文件为逗号分隔符文件,这里根据逗号切分//// String last = item[item.length-1];//这就是你要的数据了//// if(last.contains(")")){// System.out.println(Double.valueOf(last.split(",")[12])-Double.valueOf(last.split(",")[22]));// }// }// } catch (Exception e) {// e.printStackTrace();// }// }public static HashMap<String, Double> getDetailOrder(String filePath) {HashMap<String, Double> map = new HashMap<String, Double>();try {BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "gbk"));reader.read();// 第一行信息,为标题信息,不用,如果需要,注释掉String line = null;while ((line = reader.readLine()) != null) {String item[] = line.split("\r\n");// CSV格式文件为逗号分隔符文件,这里根据逗号切分
String last = item[item.length - 1];// 这就是你要的数据了if (last.contains(")")) {map.put(last.split(",")[0],Double.valueOf(last.split(",")[12])- Double.valueOf(last.split(",")[22]));}}} catch (Exception e) {e.printStackTrace();}return map;}/*** 根绝类型获取指定行的数据* * @param type* @return*/public static Double getMoney(String type, String filePath) {Double money = null;try {BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "gbk"));reader.read();//
            String line = null;while ((line = reader.readLine()) != null) {String item[] = line.split("\r\n");String last = item[item.length - 1];if (last.contains("合计")) {String[] strs = last.split(",");money = Double.valueOf(strs[strs.length - 1]);}}} catch (Exception e) {e.printStackTrace();}return money;}}

转载于:https://www.cnblogs.com/zgghb/p/5972972.html

支付宝对账查询+文件下载+解压+遍历文件+读文件相关推荐

  1. Java 支付宝对账功能(查询+文件下载+解压+遍历文件+读文件)

    Java 支付宝对账功能(查询+文件下载+解压+遍历文件+读文件) **需求** **流程** 1 .调用支付宝接口, 获取zip 下载地址 2.工具类代码 3.目录 4.开发环境 5.更新实际收益到 ...

  2. C# 支付宝对账功能(查询+文件下载+解压+遍历文件+读文件)

    C# 支付宝对账功能(查询+文件下载+解压+遍历文件+读文件) **需求** **流程** 1 .调用支付宝接口, 获取zip 下载地址 2.工具代码 需求 定时任务:每天统计昨天的公司支付宝账户实际 ...

  3. 支付宝(查询对账单下载地址+文件下载+解压+遍历文件+读文件)

    1 .调用支付宝接口, 获取zip 下载地址 package com.ycmedia.task;import com.alibaba.fastjson.JSON; import com.alibaba ...

  4. Java解压上传zip或rar文件,并解压遍历文件中的html的路径

    1.本文只提供了一个功能的代码 public String addFreeMarker() throws Exception {HttpSession session = request.getSes ...

  5. 【Google Play】APK 扩展包 ( 2021年09月 最新处理方案 | 文件准备 | 拷贝文件至内置存储 | 解压及使用扩展文件 )

    文章目录 前言 一.文件准备 二.拷贝文件至内置存储 三.解压及使用扩展文件 四.博客资源 前言 在上一篇博客 [Google Play]APK 扩展包 ( 2021年09月02日最新处理方案 | 内 ...

  6. 【Android 安全】DEX 加密 ( Java 工具开发 | 加密解密算法 API | 编译代理 Application 依赖库 | 解压依赖库 aar 文件 )

    文章目录 一.加密解密算法 API 二.编译代理 Application 依赖库 三.解压代理 Application 依赖库 aar 文件 参考博客 : [Android 安全]DEX 加密 ( 常 ...

  7. 解压上传zip文件并获取excel表数据

    1.maven <!-- 解压rar --><dependency><groupId>com.github.junrar</groupId><ar ...

  8. php tar.gz文件,PHP解压tar.gz格式文件的方法,_PHP教程

    PHP解压tar.gz格式文件的方法, 本文实例讲述了PHP解压tar.gz格式文件的方法.分享给大家供大家参考,具体如下: 1.运用php自带压缩与归档扩展(phar) $phar = new Ph ...

  9. 如何解压POSIX tar archive文件

    下载了一个xxx.gz的文件,使用x xxx.gz(zsh的x插件,十分之好用,再也不用担心tar后面该加哪些参数了)的命令解压,然后出现了一个文件,本以为解压后是一个文件夹:然后一脸蒙逼~ 突然又想 ...

最新文章

  1. 皮一皮:你住的小区叫什么名字?
  2. Notepad++如何编译、运行Java
  3. Python闭包与装饰器
  4. opencv交通标志识别_教你从零开始做一个基于深度学习的交通标志识别系统
  5. ST2-045 For POC
  6. SSL/TLS 以及HTTPS 介绍
  7. 优先级队列——实现二维数组排序
  8. 基于Java+Springmvc+vue+element实现大学生科技创新创业项目管理系统
  9. 禁用EnableViewState和启用EnableViewStat时请注意
  10. PRINCE2和PMP体系架构有何区别
  11. NOIP2017普及组★跳房子
  12. ProSpec Persephin小鼠重组体解决方案
  13. cve查询_CVE年满21岁:如何实现这一里程碑
  14. three.js obj模型的mtl材质贴图不显示
  15. android-b9是什么设备,Android 设备上可以实现 3D Touch 吗?| 原力计划
  16. 阿里云机器学习PAI-快速上手指南
  17. python根据json数据画疫情分布地图
  18. Android开发必备工具
  19. java实现Excel文件解析---apache POI以及把汉字转化为拼音
  20. 《一问一世界》 杨澜

热门文章

  1. 80 Gbps 的 USB4 2.0 要来了!
  2. [shell]计算闺年
  3. 读书笔记-程序员修炼之道-注重实效的哲学(二)
  4. 《谁的青春不迷茫》随记
  5. 《Adobe After Effects CS4经典教程》——1 工作流程 1.1 开始
  6. Windows流氓软件残留文件强制清除基于命令行
  7. ubuntu远程连接练习:
  8. 线性代数 --- 线性方程组的相容与不相容(个人笔记扫描版)
  9. 互联网大佬们的创业重要选择时刻
  10. 基于php后台的购物商城微信小程序的设计与实现