好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java中压缩文件并下载的实例详解

当我们对一些需要用到的资料进行整理时,会发现文件的内存占用很大,不过是下载或者存储,都不是很方便,这时候我们会想到把文件变成zip格式,即进行压缩。在正式开始压缩和下载文件之前,我们可以先对zip的格式进行一个了解,然后再就具体的方法给大家带来分享。

1、ZIP文件格式

[local file header + file data + data descriptor]{1,n} + central directory + end of central directory record

[文件头+文件数据+数据描述符]{此处可重复n次}+核心目录+目录结束标识当压缩包中有多个文件时,就会有多个[文件头+文件数据+数据描述符]

2、压缩和下载步骤

(1)创建压缩包前准备

//定义压缩包存在服务器的路径   String path = request.getSession().getServletContext().getRealPath( "/WEB-INF/fileTemp" );  //创建路径   File FilePath =  new  File(path +  "/file" );  if  (!FilePath.exists()) {  FilePath.mkdir();  }  String path = FilePath.getPath() +  "/" ;  //定义导出压缩包的名称   String title = "问价压缩包" ;  //压缩包格式   String fileNamezip = title +  ".zip" ;  String zipPath = path + fileNamezip;  //创建一个ZIP输出流并实例化缓冲区域   ZipOutputStream out =  new  ZipOutputStream( new  BufferedOutputStream( new  FileOutputStream(zipPath)));  //设置编码格式(解决linux出现乱码)   out.setEncoding( "gbk" );  //定义字节数组   byte  data[] =  new   byte [2048];  //获取文件记录(获取文件记录代码省略)   List FileList =。。。;  if  (!FileList.isEmpty()) {  ExportUtil util =  new  ExportUtil(title,title,  request, response, FilePath.getPath());  } 

(2)删除压缩包之前的数据,创建压缩包

?

1

util.startZip(FilePath.getPath());

(3)循环将需要压缩的文件放到压缩包中

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

for ( int i = 0 ; i < FileList.size(); i++) {

fileVo fileVo=FileList.get(i);

export(fileVo,request,response,title,FilePath.getPath(),fileName);

}

------

public void export(fileVo fileVo, HttpServletRequest request,

HttpServletResponse response, String title,String path, String fileName) {

FileOutputStream fileOutputStream = null ;

try {

File dirFile = null ;

int i = fileVo.getName().lastIndexOf( "." );

     if (i!=- 1 ){ //存在文件类型

      fileName1 = fileName1 + "." + (fileVo.getName()).substring(i+ 1 );

     }

boolean bFile = false ;

String mkdirName = path + File.separatorChar + title;

dirFile = new File(mkdirName);

if (!dirFile.exists()) {

dirFile.getParentFile().mkdirs();

}

if (dirFile.isDirectory()) {

path = mkdirName + File.separatorChar + fileName1;

} else {

bFile = dirFile.mkdirs();

}

if (bFile) {

path = mkdirName + File.separatorChar + fileName1;

}

fileOutputStream = new FileOutputStream(path.replace( "*" , "" ));

String fileName = URLEncoder.encode(fileName1, "UTF-8" );

if (fileName.length() > 110 ) {

fileName = new String(fileName1.getBytes( "gb2312" ), "ISO8859-1" );

}

response.setHeader( "Connection" , "close" );

response.setHeader( "Content-Type" , "application/octet-stream" );

response.setContentType( "application/x-msdownload" );

response.setHeader( "Content-Disposition" , "attachment; filename=""

+ Utf8Util.toUtf8String(fileName) + """ );

//读取文件流输出到到另一个位置

fileVo.getFileIo(fileOutputStream);

fileOutputStream.close();

} catch (Exception e) {

logger.error( "异常:原因如下" +e.getMessage(), e);

} finally {

try {

if (fileOutputStream != null ) {

fileOutputStream.close();

}

} catch (IOException e1) {

// TODO Auto-generated catch block

logger.error( "异常:原因如下" +e1.getMessage(), e1);

}

}

}

(4)压缩完成,关闭输出流。

?

1

util.entdZip(FilePath.getPath());

java生成压缩文件示例代码扩展

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import org.apache.tools.zip.ZipEntry;

import org.apache.tools.zip.ZipOutputStream;

/**

  * @project: Test

  * @author chenssy

  * @date 2013-7-28

  * @Description: 文件压缩工具类

  *                   将指定文件/文件夹压缩成zip、rar压缩文件

  */

public class CompressedFileUtil {

     /**

      * 默认构造函数

      */

     public CompressedFileUtil(){

 

     }

     /**

      * @desc 将源文件/文件夹生成指定格式的压缩文件,格式zip

      * @param resourePath 源文件/文件夹

      * @param targetPath  目的压缩文件保存路径

      * @return void

      * @throws Exception

      */

     public void compressedFile(String resourcesPath,String targetPath) throws Exception{

         File resourcesFile = new File(resourcesPath);     //源文件

         File targetFile = new File(targetPath);           //目的

         //如果目的路径不存在,则新建

         if (!targetFile.exists()){    

             targetFile.mkdirs(); 

         }

 

         String targetName = resourcesFile.getName()+ ".zip" ;   //目的压缩文件名

         FileOutputStream outputStream = new FileOutputStream(targetPath+ "\" +targetName);

         ZipOutputStream out = new ZipOutputStream( new BufferedOutputStream(outputStream));

 

         createCompressedFile(out, resourcesFile, "" );

 

         out.close(); 

     }

 

     /**

      * @desc 生成压缩文件。

      *                  如果是文件夹,则使用递归,进行文件遍历、压缩

      *       如果是文件,直接压缩

      * @param out  输出流

      * @param file  目标文件

      * @return void

      * @throws Exception

      */

     public void createCompressedFile(ZipOutputStream out,File file,String dir) throws Exception{

         //如果当前的是文件夹,则进行进一步处理

         if (file.isDirectory()){

             //得到文件列表信息

             File[] files = file.listFiles();

             //将文件夹添加到下一级打包目录

             out.putNextEntry( new ZipEntry(dir+ "/" ));

 

             dir = dir.length() == 0 ? "" : dir + "/" ;

 

             //循环将文件夹中的文件打包

             for ( int i = 0 ; i < files.length ; i++){

                 createCompressedFile(out, files[i], dir + files[i].getName());         //递归处理

             }

         }

         else {   //当前的是文件,打包处理

             //文件输入流

             FileInputStream fis = new FileInputStream(file);

 

             out.putNextEntry( new ZipEntry(dir));

             //进行写操作

             int j =  0 ;

             byte [] buffer = new byte [ 1024 ];

             while ((j = fis.read(buffer)) > 0 ){

                 out.write(buffer, 0 ,j);

             }

             //关闭输入流

             fis.close();

         }

     }

 

     public static void main(String[] args){

         CompressedFileUtil compressedFileUtil = new CompressedFileUtil();

 

         try {

             compressedFileUtil测试数据pressedFile( "G:\zip" , "F:\zip" );

             System.out.println( "压缩文件已经生成..." );

         } catch (Exception e) {

             System.out.println( "压缩文件生成失败..." );

             e.printStackTrace();

         }

     }

}

到此这篇关于java中压缩文件并下载的实例详解的文章就介绍到这了,更多相关如何在java中压缩文件并下载内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://HdhCmsTestpy.cn/java/download/23821.html

查看更多关于java中压缩文件并下载的实例详解的详细内容...

  阅读:24次