Java compresses multiple files and returns a stream example

  • 2020-04-01 03:09:47
  • OfStack

This class can compress multiple files and return to the stream. In the program, the returned stream can be manipulated to do other functions, such as verifying MD5


/**
*  Method description: <b> The test class </b></br>
*/
public class TestFileStream{
 //Where files and compressed packages are stored
StringtempFilePath="C:/temp/"
List<String>fileList=newArrayList<String>();
fileList.add(tempFilePath+"file1.txt");
fileList.add(tempFilePath+"file2.png");
fileList.add(tempFilePath+"file3.xls");
//Name of the generated zip
StringzipName="fileData";
//Return flow
ByteArrayOutputStreamoutputStream=fileToZip(fileList,fileData,tempFilePath);
//Page input compressed package stream
byte[]buffer=outputStream.toByteArray();
//To empty the response
response.reset();
//Set the Header for response
response.addHeader("Content-Disposition",
"attachment;filename="+
newString(("dataFile.zip").getBytes("gb2312"),"ISO8859-1"));
response.addHeader("Content-Length",""+outputStream.size());
toClient=newBufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
}
/**
* Method description: <b> Compress multiple files into zip package </b></br>
*/
publicByteArrayOutputStreamfileToZip(List<String>fileList,StringzipName,StringtempFilePath){
byte[]buffer=newbyte[1024];
ZipOutputStreamout=null;
try{
out=newZipOutputStream(newFileOutputStream(tempFilePath+zipName+".zip"));
List<File>filedata=newArrayList<File>();
for(inti=0,len=fileList.size();i<len;i++)
{
filedata.add(newFile(fileList.get(i)));
}
for(intj=0,len=filedata.size();j<len;j++)
{
FileInputStreamfis=newFileInputStream(filedata.get(j));
out.putNextEntry(newZipEntry(filedata.get(j).getName()));
intdataLen;
//Read in the contents of the file you want to download and package it into a zip file
while((dataLen=fis.read(buffer))>0){
out.write(buffer,0,dataLen);
}
out.closeEntry();
fis.close();
}
out.close();
}
catch(Exceptionex)
{
ex.printStackTrace();
}
//Read package
Filefilezip=newFile(tempFilePath+zipName+".zip");
ByteArrayOutputStreambaos=null;
try
{
baos=newByteArrayOutputStream();
FileInputStreaminStream=newFileInputStream(filezip);
BufferedInputStreambis=newBufferedInputStream(inStream);
intc=bis.read();
while(c!=-1){
baos.write(c);
c=bis.read();
}
bis.close();
inStream.close();
}
catch(Exceptionex)
{
ex.printStackTrace();
}
returnbaos;
}


Related articles: