Java實(shí)現(xiàn)批量下載文件的示例代碼
我需要調(diào)取第三方接口的數(shù)據(jù)存到本地服務(wù)器上,然后在以輸出流的形式響應(yīng)
zipUtil(工具類,直接復(fù)制即可,這個(gè)是我從別的博主那里復(fù)制來的,親測有效)
public class ZipUtil {
private static Logger logger = LoggerFactory.getLogger(ZipUtils.class);
// 目錄標(biāo)識(shí)判斷符
public static final String PATCH = "/";
// 基目錄
public static final String BASE_DIR = "";
// 緩沖區(qū)大小
private static final int BUFFER = 2048;
// 字符集
public static final String CHAR_SET = "GBK";
/**
*
* 描述: 壓縮文件
* @author wanghui
* @created 2017年10月27日
* @param fileOutName
* @param files
* @throws Exception
*/
public static void compress(String fileOutName, List<File> files) throws Exception {
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileOutName);
ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
zipOutputStream.setEncoding(CHAR_SET);
if (files != null && files.size() > 0) {
for (int i = 0,size = files.size(); i < size; i++) {
compress(files.get(i), zipOutputStream, BASE_DIR);
}
}
// 沖刷輸出流
zipOutputStream.flush();
// 關(guān)閉輸出流
zipOutputStream.close();
} catch (Exception e) {
throw new Exception(e.getMessage(),e);
}
}
/**
*
* 描述:壓縮文件并進(jìn)行Base64加密
* @author wanghui
* @created 2017年10月27日
* @param files
* @return
* @throws Exception
*/
public static String compressToBase64(List<File> files) throws Exception {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(bos);
zipOutputStream.setEncoding(CHAR_SET);
if (files != null && files.size() > 0) {
for (int i = 0,size = files.size(); i < size; i++) {
compress(files.get(i), zipOutputStream, BASE_DIR);
}
}
// 沖刷輸出流
zipOutputStream.flush();
// 關(guān)閉輸出流
zipOutputStream.close();
byte[] data = bos.toByteArray();
return new String(Base64.encodeBase64(data));
} catch (Exception e) {
throw new Exception(e.getMessage(),e);
}
}
/**
*
* 描述: 壓縮
* @author wanghui
* @created 2017年10月27日
* @param srcFile
* @param zipOutputStream
* @param basePath
* @throws Exception
*/
public static void compress(File srcFile, ZipOutputStream zipOutputStream, String basePath) throws Exception {
if (srcFile.isDirectory()) {
compressDir(srcFile, zipOutputStream, basePath);
} else {
compressFile(srcFile, zipOutputStream, basePath);
}
}
/**
*
* 描述:壓縮目錄下的所有文件
* @author wanghui
* @created 2017年10月27日
* @param dir
* @param zipOutputStream
* @param basePath
* @throws Exception
*/
private static void compressDir(File dir, ZipOutputStream zipOutputStream, String basePath) throws Exception {
try {
// 獲取文件列表
File[] files = dir.listFiles();
if (files.length < 1) {
ZipEntry zipEntry = new ZipEntry(basePath + dir.getName() + PATCH);
zipOutputStream.putNextEntry(zipEntry);
zipOutputStream.closeEntry();
}
for (int i = 0,size = files.length; i < size; i++) {
compress(files[i], zipOutputStream, basePath + dir.getName() + PATCH);
}
} catch (Exception e) {
throw new Exception(e.getMessage(), e);
}
}
/**
*
* 描述:壓縮文件
* @author wanghui
* @created 2017年10月27日
* @param file
* @param zipOutputStream
* @param dir
* @throws Exception
*/
private static void compressFile(File file, ZipOutputStream zipOutputStream, String dir) throws Exception {
try {
// 壓縮文件
ZipEntry zipEntry = new ZipEntry(dir + file.getName());
zipOutputStream.putNextEntry(zipEntry);
// 讀取文件
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
int count = 0;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
zipOutputStream.write(data, 0, count);
}
bis.close();
zipOutputStream.closeEntry();
} catch (Exception e) {
throw new Exception(e.getMessage(),e);
}
}
/**
*
* 描述: 文件Base64加密
* @author wanghui
* @created 2017年10月27日 上午9:27:38
* @param srcFile
* @return
* @throws Exception
*/
public static String encodeToBASE64(File srcFile) throws Exception {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// 讀取文件
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
int count = 0;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
bos.write(data, 0, count);
}
bis.close();
byte[] base64Data = Base64.encodeBase64(bos.toByteArray());
if (null == base64Data) {
bos.close();
return null;
}
bos.close();
return new String(base64Data, CHAR_SET);
} catch (Exception e) {
throw new Exception(e.getMessage(),e);
}
}
/**
*
* 描述: 文件Base64解密
* @author wanghui
* @created 2017年10月27日
* @param destFile
* @param encodeStr
* @throws Exception
*/
public static void decodeToBase64(File destFile, String encodeStr) throws Exception {
try {
byte[] decodeBytes = Base64.decodeBase64(encodeStr.getBytes());
ByteArrayInputStream bis = new ByteArrayInputStream(decodeBytes);
// 讀取文件
FileOutputStream fileOutputStream = new FileOutputStream(destFile);
int count = 0;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
fileOutputStream.write(data, 0, count);
}
fileOutputStream.close();
bis.close();
} catch (Exception e) {
throw new Exception(e.getMessage(),e);
}
}
/**
*
* 描述: 解壓縮
* @author wanghui
* @created 2017年10月27日
* @param srcFileName
* @param destFileName
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static void decompress(String srcFileName, String destFileName) throws Exception {
try {
ZipFile zipFile = new ZipFile(srcFileName);
Enumeration<ZipEntry> entries = zipFile.getEntries();
File destFile = new File(destFileName);
InputStream inputStream = null;
while(entries.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry)entries.nextElement();
String dir = destFile.getPath() + File.separator + zipEntry.getName();
File dirFile = new File(dir);
if (zipEntry.isDirectory()) {
dirFile.mkdirs();
} else {
fileProber(dirFile);
inputStream = zipFile.getInputStream(zipEntry);
decompressFile(dirFile, inputStream);
}
}
zipFile.close();
} catch (Exception e) {
throw new Exception(e.getMessage(),e);
}
}
/**
*
* 描述: 解壓文件
* @author wanghui
* @created 2017年10月27日
* @param destFile
* @param inputStream
* @throws Exception
*/
private static void decompressFile(File destFile, InputStream inputStream) throws Exception {
try {
// 文件輸入流
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
int count = 0;
byte data[] = new byte[BUFFER];
while ((count = inputStream.read(data, 0, BUFFER)) != -1) {
bos.write(data, 0, count);
}
bos.close();
inputStream.close();
} catch (Exception e) {
throw new Exception(e.getMessage(), e);
}
}
/**
*
* 描述:文件探測
* @author wanghui
* @created 2017年10月27日
* @param dirFile
*/
private static void fileProber(File dirFile) {
File parentFile = dirFile.getParentFile();
if (!parentFile.exists()) {
// 遞歸尋找上級目錄
fileProber(parentFile);
parentFile.mkdir();
}
}
/**
* 遞歸刪除目錄下的所有文件及子目錄下所有文件
* @param dir 將要?jiǎng)h除的文件目錄
* @return boolean Returns "true" if all deletions were successful.
* If a deletion fails, the method stops attempting to
* delete and returns "false".
*/
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
//遞歸刪除目錄中的子目錄下
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// 目錄此時(shí)為空,可以刪除
return dir.delete();
}Controller層
public void bathDownScript(HttpServletResponse response, String paths) throws Exception {
String uuid = UUID.randomUUID().toString().replaceAll("-","");
//1.新建文件夾,用來存放下載下來的文件,最后進(jìn)行壓縮
File folder = new File("/tmp/"+uuid);
System.out.println(folder.getName());
if (!folder.exists() && !folder.isDirectory()) {
boolean flag = folder.mkdirs();
}
//2.遍歷讀取文件放入文件夾中
String[] path= paths.split(",");
Configuration conf = new Configuration();
conf.set("fs.defaultFS", HdfsUtils.HDFSURL);
List<File> files = new ArrayList<File>();
for(String huePath:path){
//通過hdfs讀取文件
byte[] res = HdfsUtils.readFile(conf,huePath);
//定義文件名稱
String fileName = huePath.substring(huePath.lastIndexOf("/"));
//定義文件路徑
File f = new File("/tmp/"+uuid+fileName);
InputStream in = new ByteArrayInputStream(res);
byte[] buff = new byte[1024];
FileOutputStream out = new FileOutputStream(f);
try {
int i = in.read(buff);
while (i != -1) {
out.write(buff, 0, buff.length);
out.flush();
i = in.read(buff);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
files.add(f);
}
//3.響應(yīng)前端數(shù)據(jù)
String zipName = "myfile.zip";
response.setHeader("content-type", "application/octet-stream");
response.setCharacterEncoding("utf-8");
// 設(shè)置瀏覽器響應(yīng)頭對應(yīng)的Content-disposition
response.setHeader("Content-disposition",
"attachment;filename=" + new String(zipName.getBytes("gbk"), "iso8859-1"));
ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());
zipOutputStream.setEncoding(ZipUtil.CHAR_SET);
if (CollectionUtils.isEmpty(files) == false) {
for (int i = 0,size = files.size(); i < size; i++) {
ZipUtil.compress(files.get(i), zipOutputStream, ZipUtil.BASE_DIR);
}
}
// 沖刷輸出流
zipOutputStream.flush();
// 關(guān)閉輸出流
zipOutputStream.close();
//4.下載完刪除deleteDir
boolean flag = ZipUtil.deleteDir(folder);
System.out.println("刪除文件:"+flag);
}以上就是Java實(shí)現(xiàn)批量下載文件的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于Java批量下載文件的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java使用Condition控制線程通信的方法實(shí)例詳解
這篇文章主要介紹了Java使用Condition控制線程通信的方法,結(jié)合實(shí)例形式分析了使用Condition類同步檢測控制線程通信的相關(guān)操作技巧,需要的朋友可以參考下2019-09-09
基于apache poi根據(jù)模板導(dǎo)出excel的實(shí)現(xiàn)方法
下面小編就為大家?guī)硪黄赼pache poi根據(jù)模板導(dǎo)出excel的實(shí)現(xiàn)方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-06-06
springboot json時(shí)間格式化處理的方法
這篇文章主要介紹了springboot json時(shí)間格式化處理的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-03-03
java用兩個(gè)例子充分闡述多態(tài)的可拓展性介紹
下面小編就為大家?guī)硪黄猨ava用兩個(gè)例子充分闡述多態(tài)的可拓展性介紹。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-06-06
springboot?vue接口測試HutoolUtil?TreeUtil處理樹形結(jié)構(gòu)
這篇文章主要介紹了springboot?vue接口測試HutoolUtil?TreeUtil處理樹形結(jié)構(gòu),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
數(shù)據(jù)庫CURD必備搭檔mybatis?plus詳解
這篇文章主要為大家介紹了數(shù)據(jù)庫CURD必備搭檔mybatis?plus詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
SpringBoot集成分頁插件PageHelper的配置和使用過程
這篇文章主要介紹了SpringBoot集成分頁插件PageHelper的配置和使用過程,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-04-04
詳解使用Spring?Data?repository進(jìn)行數(shù)據(jù)層的訪問問題
這篇文章主要介紹了使用Spring?Data?repository進(jìn)行數(shù)據(jù)層的訪問,抽象出Spring Data repository是因?yàn)樵陂_發(fā)過程中,常常會(huì)為了實(shí)現(xiàn)不同持久化存儲(chǔ)的數(shù)據(jù)訪問層而寫大量的大同小異的代碼,本文給大家介紹的非常詳細(xì),需要的朋友參考下吧2022-06-06

