记录文件下载,并解压缩的功能逻辑为主,引用支付宝对接,工具类主要
1支付宝下载文件解压
import com.alipay.api.AlipayClient;
public vid aliPayBills(String billDate, PayAccountConfig accountConfig) throws Exception {
AlipayClient alipayClient = getInstance();
AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();
Map<String, String> params = new HashMap<>();
params.put("bill_type", "signcustomer");
params.put("bill_date", billDate);
request.setBizContent(JSON.toJSONString(params));
AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient.certificateExecute(request);
if (response.isSuccess()) {
String payBillsPath = aliPayBillsPath;
//获取支付宝对账单URL(url有效时间为30秒)
String url = response.getBillDownloadUrl();
log.info("***************获取到的支付宝对账单的URL:" + url + "**********************");
String newZip = payBillsPath + new Date().getTime() + ".zip";
// 开始下载 (下载文件为zip)
SaveFile.downloadNet(url, newZip, payBillsPath);
//解压(解压后有两个文件,明细,明细汇总)
SaveFile.unZip(newZip, payBillsPath);
log.info("***************下载,解压完成**********************");
//获取解压后的两个文件
File[] fs = new File(payBillsPath).listFiles();
//用来保存明细的数据
ArrayList<String[]> csvList = new ArrayList<>();
String fileName = "";
//获取对账单明细(只需要处理明细文件)
for (File file : fs) {
if (!file.getAbsolutePath().contains("汇总") && !file.getAbsolutePath().contains("zip")) {
fileName = file.getAbsolutePath();
//csvList = getFileCell(fileName);
}
}
File file2 = new File(fileName);
FileInputStream inputStream = new FileInputStream(file2);
MultipartFile multipartFile = new MockMultipartFile(file2.getName(), file2.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
String originalFilename = multipartFile.getOriginalFilename();
OssUtil.uploadFile(bucketName, originalFilename, multipartFile, "/paybills");
for (File file : fs) {
if (file.isFile()) {
SaveFile.delFile(file.getAbsolutePath());
} else {
SaveFile.delFolder(file.getAbsolutePath());
}
}
return csvList;
} else {
System.out.println("调用失败");
return null;
}
}
2.工具类
package com.tsll.feegl.service.impl;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
//import java.util.zip.ZipFile;
public class SaveFile {
/**
* 使用GBK编码可以避免压缩中文文件名乱码
*/
private static final String CHINESE_CHARSET = "GBK";
/**
* 文件读取缓冲区大小
*/
private static final int CACHE_SIZE = 1024;
/**
* 根据Url下载文件
*
* @param urlStr
* @param fileName
* @param savePath
* @throws IOException
*/
public static void downLoadFromUrl(String urlStr, String fileName,
String savePath) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
//获取自己数组
byte[] getData = readInputStream(inputStream);
//文件保存位置
File saveDir = new File(savePath);
if (!saveDir.exists()) {
saveDir.mkdir();
}
File file = new File(saveDir + File.separator + fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
if (fos != null) {
fos.close();
}
if (inputStream != null) {
inputStream.close();
}
//log.info("info: {} download success ", url);
}
public static void delFile(String path) {
File file = new File(path);
if (!file.exists()) return;
if (file.isFile() || file.list() == null) {
file.delete();
// log.info("the file:{} has been deleted", file.getName());
}
}
public static void delFolder(String folderPath) {
try {
delAllFile(folderPath); // 删除完里面所有内容
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
myFilePath.delete(); // 删除空文件夹
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean delAllFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
delFolder(path + "/" + tempList[i]);// 再删除空文件夹
flag = true;
}
}
return flag;
}
/**
* 从输入流中获取字节数组
*
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
public static void downloadNet(String path, String filePath,String filePath1)
throws MalformedURLException {
// 下载网络文件
int bytesum = 0;
int byteread = 0;
URL url = new URL(path);
//文件保存位置
File saveDir = new File(filePath1);
if (!saveDir.exists()) {
saveDir.mkdir();
}
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();
}
}
/**
* 解压到指定目录
*
* @param zipFilePath
* @param destDir
* @throws Exception
*/
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((ZipArchiveEntry) 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();
}
}
版权声明:本文为qq_37714654原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。