導航:首頁 > 文件處理 > java循環下載壓縮文件

java循環下載壓縮文件

發布時間:2022-06-03 16:32:43

『壹』 java 如何一次下載多個文件

創建多線程下載
如果說方便下載,是打包再下載
~~~~~~~~~~~~~~~~~~~~~~

『貳』 JAVA 批量下載.zip

/**
* 報表查詢模塊 ----文件下載流
* @return
* @throws IOException
*/
public InputStream getInputStream() throws IOException {
InputStream ins = new FileInputStream(zipReports());
return ins;
}

/**
* 根據傳過來的報表編號壓縮文件為zip
* @param response
* @param serverPath
* @param str
* @throws IOException
*/
public File zipReports() throws IOException{
List<StatisticalReport> srclist = new ArrayList<StatisticalReport>();
String[] pks = ids.split(",");
if(pks.length > 0){
for(String pk : pks){
String[] str = pk.split("\\|");
StatisticalReport obj = new StatisticalReport();
obj.setCendat(str[0]);
obj.setOrgidt(str[1]);
obj.setRep_code(str[2]);
obj.setCurcde(str[3]);
srclist.add(obj);
}
}
StatisticalReport obj = new StatisticalReport();
obj.setReportList(srclist);
//查詢要下載的報表文件
List<StatisticalReport> list = statisticalReportService.findReportList(obj);
//獲取應用在伺服器上的根目錄
String path = request.getSession().getServletContext().getRealPath(System.getProperty("file.separator"));
List<File> srcList = new ArrayList<File>();
if(list.size() > 0){
for(StatisticalReport statisticalReport : list){
File file = new File(statisticalReport.getFile_path());
if(file.exists()){
srcList.add(file);
}
}
}

Pim_sysUser user = (Pim_sysUser) session.getAttribute(SysConstant.SESSION_USER_DATA);
File zipfile = new File(path + System.getProperty("file.separator") + user.getLogid() + "REPORT.zip");
if(zipfile.exists()){
zipfile.delete();
zipfile.createNewFile();
}
//FileTools.File(, res.getString("help_path"), newFormatFileName);// 上傳文件
ZipUtils.zipFiles(srcList, zipfile);
return zipfile;
}

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipUtils {
/**
* 將多個Excel打包成zip文件
*
* @param srcfile
* @param zipfile
*/
public static void zipFiles(List<File> srcfile, File zipfile) {
byte[] buf = new byte[2048];
try {
// Create the ZIP file
// Compress the files
if(srcfile.size() > 0){
// 創建ZipOutputStream類對象
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
for (int i = 0; i < srcfile.size(); i++) {
File file = srcfile.get(i);
FileInputStream in = new FileInputStream(file);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(file.getName()));// 寫入此目錄的Entry 創建新的進入點
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
out.setLevel(9);
out.write(buf, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
}
out.close();
}else{
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
out.putNextEntry(new ZipEntry(" "));
out.closeEntry();
out.close();
}
// Complete the ZIP file
} catch (IOException e) {
e.printStackTrace();
}
}
}

『叄』 高分:用java實現伺服器上多個文件先打包,然後下載,下載完成後刪除包!

jdk有個包--- java.util.jar
1 這個包里的類可以打包文件,具體做法可以參考API,看你的水平 通過API了解新類 應該不是問題了。
2 刪除文件--不用說了吧,file.delete.....
3 下載就更加簡單了, 用「流」將文件輸出就可以了。

再不行??? 信息我吧。 但是不會給你源代碼 只有給你思路了。

『肆』 急!!!想實現通過java方式壓縮文件並提供下載功能,在線等!!!

給你一個代碼吧。
/**
* 文件夾壓縮。輸入路徑不能與輸出路徑相同
* zip("c:\\webserver\\test.zip","c:\\test1");
* @param zipFileName
* @param inputFile
* @throws Exception
*/
public static void zipFold(String zipFileName,String inputFilePath)throws Exception{
zip(zipFileName,new File(inputFilePath));
}

private static void zip(String zipFileName,File inputFile)throws Exception{
ZipOutputStream out=new ZipOutputStream(new FileOutputStream(zipFileName));
zipFold(out,inputFile,"");
out.close();
}

private static void zipFold(ZipOutputStream out,File f,String base)throws Exception{
if (f.isDirectory())
{
File[] fl=f.listFiles();
base=base.length()==0?"":base+"/";
for (int i=0;i<fl.length ;i++ )
{
zipFold(out,fl[i],base+fl[i].getName());
}
}
else
{
out.putNextEntry(new ZipEntry(base));
FileInputStream in=new FileInputStream(f);
int b;
while ((b=in.read()) != -1)
out.write(b);
in.close();
}
}

『伍』 java怎麼下載壓縮文件

可以用java的輸入,輸出流,設置返回的類型為下轉
response.setContentType("application/x-download");//設置為下載application/x-download
String filedownload = "/要下載的文件名";//即將下載的文件的相對路徑
String filedisplay = "最終要顯示給用戶的保存文件名";//下載文件時顯示的文件保存名稱
String filenamedisplay = URLEncoder.encode(filedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filedisplay);

『陸』 怎樣用java快速實現zip文件的壓縮解壓

packagezip;
importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.util.Enumeration;
importjava.util.zip.CRC32;
importjava.util.zip.CheckedOutputStream;
importjava.util.zip.ZipEntry;
importjava.util.zip.ZipFile;
importjava.util.zip.ZipOutputStream;
importorg.apache.commons.lang3.StringUtils;
publicclassZipUtil{

/**
*遞歸壓縮文件夾
*@paramsrcRootDir壓縮文件夾根目錄的子路徑
*@paramfile當前遞歸壓縮的文件或目錄對象
*@paramzos壓縮文件存儲對象
*@throwsException
*/
privatestaticvoidzip(StringsrcRootDir,Filefile,ZipOutputStreamzos)throwsException
{
if(file==null)
{
return;
}

//如果是文件,則直接壓縮該文件
if(file.isFile())
{
intcount,bufferLen=1024;
bytedata[]=newbyte[bufferLen];

//獲取文件相對於壓縮文件夾根目錄的子路徑
StringsubPath=file.getAbsolutePath();
intindex=subPath.indexOf(srcRootDir);
if(index!=-1)
{
subPath=subPath.substring(srcRootDir.length()+File.separator.length());
}
ZipEntryentry=newZipEntry(subPath);
zos.putNextEntry(entry);
BufferedInputStreambis=newBufferedInputStream(newFileInputStream(file));
while((count=bis.read(data,0,bufferLen))!=-1)
{
zos.write(data,0,count);
}
bis.close();
zos.closeEntry();
}
//如果是目錄,則壓縮整個目錄
else
{
//壓縮目錄中的文件或子目錄
File[]childFileList=file.listFiles();
for(intn=0;n<childFileList.length;n++)
{
childFileList[n].getAbsolutePath().indexOf(file.getAbsolutePath());
zip(srcRootDir,childFileList[n],zos);
}
}
}

/**
*對文件或文件目錄進行壓縮
*@paramsrcPath要壓縮的源文件路徑。如果壓縮一個文件,則為該文件的全路徑;如果壓縮一個目錄,則為該目錄的頂層目錄路徑
*@paramzipPath壓縮文件保存的路徑。注意:zipPath不能是srcPath路徑下的子文件夾
*@paramzipFileName壓縮文件名
*@throwsException
*/
publicstaticvoidzip(StringsrcPath,StringzipPath,StringzipFileName)throwsException
{
if(StringUtils.isEmpty(srcPath)||StringUtils.isEmpty(zipPath)||StringUtils.isEmpty(zipFileName))
{
thrownewParameterException(ICommonResultCode.PARAMETER_IS_NULL);
}
CheckedOutputStreamcos=null;
ZipOutputStreamzos=null;
try
{
FilesrcFile=newFile(srcPath);

//判斷壓縮文件保存的路徑是否為源文件路徑的子文件夾,如果是,則拋出異常(防止無限遞歸壓縮的發生)
if(srcFile.isDirectory()&&zipPath.indexOf(srcPath)!=-1)
{
thrownewParameterException(ICommonResultCode.INVALID_PARAMETER,".");
}

//判斷壓縮文件保存的路徑是否存在,如果不存在,則創建目錄
FilezipDir=newFile(zipPath);
if(!zipDir.exists()||!zipDir.isDirectory())
{
zipDir.mkdirs();
}

//創建壓縮文件保存的文件對象
StringzipFilePath=zipPath+File.separator+zipFileName;
FilezipFile=newFile(zipFilePath);
if(zipFile.exists())
{
//檢測文件是否允許刪除,如果不允許刪除,將會拋出SecurityException
=newSecurityManager();
securityManager.checkDelete(zipFilePath);
//刪除已存在的目標文件
zipFile.delete();
}

cos=newCheckedOutputStream(newFileOutputStream(zipFile),newCRC32());
zos=newZipOutputStream(cos);

//如果只是壓縮一個文件,則需要截取該文件的父目錄
StringsrcRootDir=srcPath;
if(srcFile.isFile())
{
intindex=srcPath.lastIndexOf(File.separator);
if(index!=-1)
{
srcRootDir=srcPath.substring(0,index);
}
}
//調用遞歸壓縮方法進行目錄或文件壓縮
zip(srcRootDir,srcFile,zos);
zos.flush();
}
catch(Exceptione)
{
throwe;
}
finally
{
try
{
if(zos!=null)
{
zos.close();
}
}
catch(Exceptione)
{
e.printStackTrace();
}
}
}

/**
*解壓縮zip包
*@paramzipFilePathzip文件的全路徑
*@paramunzipFilePath解壓後的文件保存的路徑
*@paramincludeZipFileName解壓後的文件保存的路徑是否包含壓縮文件的文件名。true-包含;false-不包含
*/
@SuppressWarnings("unchecked")
publicstaticvoinzip(StringzipFilePath,StringunzipFilePath,booleanincludeZipFileName)throwsException
{
if(StringUtils.isEmpty(zipFilePath)||StringUtils.isEmpty(unzipFilePath))
{
thrownewParameterException(ICommonResultCode.PARAMETER_IS_NULL);
}
FilezipFile=newFile(zipFilePath);
//如果解壓後的文件保存路徑包含壓縮文件的文件名,則追加該文件名到解壓路徑
if(includeZipFileName)
{
StringfileName=zipFile.getName();
if(StringUtils.isNotEmpty(fileName))
{
fileName=fileName.substring(0,fileName.lastIndexOf("."));
}
unzipFilePath=unzipFilePath+File.separator+fileName;
}
//創建解壓縮文件保存的路徑
FileunzipFileDir=newFile(unzipFilePath);
if(!unzipFileDir.exists()||!unzipFileDir.isDirectory())
{
unzipFileDir.mkdirs();
}

//開始解壓
ZipEntryentry=null;
StringentryFilePath=null,entryDirPath=null;
FileentryFile=null,entryDir=null;
intindex=0,count=0,bufferSize=1024;
byte[]buffer=newbyte[bufferSize];
BufferedInputStreambis=null;
BufferedOutputStreambos=null;
ZipFilezip=newZipFile(zipFile);
Enumeration<ZipEntry>entries=(Enumeration<ZipEntry>)zip.entries();
//循環對壓縮包里的每一個文件進行解壓
while(entries.hasMoreElements())
{
entry=entries.nextElement();
//構建壓縮包中一個文件解壓後保存的文件全路徑
entryFilePath=unzipFilePath+File.separator+entry.getName();
//構建解壓後保存的文件夾路徑
index=entryFilePath.lastIndexOf(File.separator);
if(index!=-1)
{
entryDirPath=entryFilePath.substring(0,index);
}
else
{
entryDirPath="";
}
entryDir=newFile(entryDirPath);
//如果文件夾路徑不存在,則創建文件夾
if(!entryDir.exists()||!entryDir.isDirectory())
{
entryDir.mkdirs();
}

//創建解壓文件
entryFile=newFile(entryFilePath);
if(entryFile.exists())
{
//檢測文件是否允許刪除,如果不允許刪除,將會拋出SecurityException
=newSecurityManager();
securityManager.checkDelete(entryFilePath);
//刪除已存在的目標文件
entryFile.delete();
}

//寫入文件
bos=newBufferedOutputStream(newFileOutputStream(entryFile));
bis=newBufferedInputStream(zip.getInputStream(entry));
while((count=bis.read(buffer,0,bufferSize))!=-1)
{
bos.write(buffer,0,count);
}
bos.flush();
bos.close();
}
}

publicstaticvoidmain(String[]args)
{
StringzipPath="d:\ziptest\zipPath";
Stringdir="d:\ziptest\rawfiles";
StringzipFileName="test.zip";
try
{
zip(dir,zipPath,zipFileName);
}
catch(Exceptione)
{
e.printStackTrace();
}

StringzipFilePath="D:\ziptest\zipPath\test.zip";
StringunzipFilePath="D:\ziptest\zipPath";
try
{
unzip(zipFilePath,unzipFilePath,true);
}
catch(Exceptione)
{
e.printStackTrace();
}
}
}

『柒』 java中如何保證下載的壓縮包命名中有中文

在使用Java對ZIP壓縮文件進行解壓的方式中有兩種,一種是使用apache提供的ant.jar工具包,但是如果ZIP文件中含有中文名稱的文件,在解壓後,文件名將出現亂碼,另一種是使用Java自身JDK中java.util.zip包下工具類,但是同樣如果有中文名的情況下依然會出現亂碼情況。因此對於這種亂碼的處理,一種是修改JDK下的幾個源文件,一種就是把需要用的JDK源文件重新反編譯進行處理,單獨放在一個包中,在使用的時候,調用自己處理過的包中文件進行處理即可。附件tools.rar壓縮文件是我進行處理過後的需要調用到的java源程序,主要為Deflater.java,DeflaterOutputStream.java,InflaterInputStream.java,ZipConstants.java,ZipEntry.java,ZipInputStram.java,ZipOutputStream.java文件,同時包含一個解壓縮文件CompressZipFile.java

『捌』 java 先根據一個list生成一個文件,然後在壓縮下載怎麼實現

編碼思路
(一)封裝list集合信息使之輸出到txt、excel等文件中;
(二)通過ZipOutputStream實現對文件壓縮操作;
(三)使用HttpServlet提供與用戶進行下載,下載完成後,刪除文件。

『玖』 Java 下載文件的方法怎麼寫

參考下面
public HttpServletResponse download(String path, HttpServletResponse response) {
try {
// path是指欲下載的文件的路徑。
File file = new File(path);
// 取得文件名。
String filename = file.getName();
// 取得文件的後綴名。
String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
// 以流的形式下載文件。
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 設置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return response;
}

// 下載本地文件
public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {
String fileName = "Operator.doc".toString(); // 文件的默認保存名
// 讀到流中
InputStream inStream = new FileInputStream("c:/Operator.doc");// 文件的存放路徑
// 設置輸出的格式
response.reset();
response.setContentType("bin");
response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// 循環取出流中的數據
byte[] b = new byte[100];
int len;
try {
while ((len = inStream.read(b)) > 0)
response.getOutputStream().write(b, 0, len);
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

// 下載網路文件
public void downloadNet(HttpServletResponse response) throws MalformedURLException {
int bytesum = 0;
int byteread = 0;
URL url = new URL("windine.blogdriver.com/logo.gif");
try {
URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream();
FileOutputStream fs = new FileOutputStream("c:/abc.gif");
byte[] buffer = new byte[1204];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

//支持在線打開文件的一種方式
public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {
File f = new File(filePath);
if (!f.exists()) {
response.sendError(404, "File not found!");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0;
response.reset(); // 非常重要
if (isOnLine) { // 在線打開方式
URL u = new URL("file:///" + filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
// 文件名應該編碼成UTF-8
} else { // 純下載方式
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
}
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}

閱讀全文

與java循環下載壓縮文件相關的資料

熱點內容
山西太原php 瀏覽:271
常用cmd網路命令 瀏覽:676
hashmap7源碼分析 瀏覽:896
搜索引擎原理技術與系統pdf 瀏覽:359
運動估計演算法python 瀏覽:858
java正則1 瀏覽:536
redhatlinux最新 瀏覽:177
python字典編程詞彙 瀏覽:144
微信和伺服器如何通訊 瀏覽:10
百家號伺服器配置有什麼用 瀏覽:598
怎麼為電腦加密 瀏覽:58
伺服器出現差錯是什麼意思 瀏覽:616
蘋果app移到商店裡怎麼刪掉 瀏覽:254
phpjsphtml 瀏覽:63
吃雞手機國際服伺服器超時怎麼辦 瀏覽:68
努比亞Z5無命令 瀏覽:642
展示網站雲伺服器 瀏覽:872
代碼混淆器php 瀏覽:367
貝恩pdf 瀏覽:209
丙烯pdf 瀏覽:368