• java的实体类注解校验


    系列文章目录


    一、校验注解-- @NotNull、@NotEmpty、@NotBlank

    1.@NotNull:不能为 null,但可以为 empty,一般用在 Integer 类型的基本数据类型的非空校验上,而且被其标注的字段可以使用 @size、@Max、@Min 对字段数值进行大小的控制
    2.@NotEmpty: 不能为 null,且长度必须大于 0,一般用在集合类上或者数组上
    3.@NotBlank:只能作用在接收的 String 类型上,注意是只能,不能为 null,而且调用 trim() 后,长度必须大于 0即:必须有实际字符
    注意在使用 @NotBlank 等注解时,一定要和 @valid 一起使用,否则 @NotBlank 不起作用。
    一个 BigDecimal 的字段使用字段校验标签应该为 @NotNull。
    在使用 @Length 一般用在 String 类型上可对字段数值进行最大长度限制的控制。
    在使用 @Range 一般用在 Integer 类型上可对字段数值进行大小范围的控制。
    在这里插入图片描述
    如下示例:

    1.String name = null;
    
    @NotNull: false
    @NotEmpty:false 
    @NotBlank:false 
    
    
    
    2.String name = "";
    
    @NotNull:true
    @NotEmpty: false
    @NotBlank: false
    
    
    
    3.String name = " ";
    
    @NotNull: true
    @NotEmpty: true
    @NotBlank: false
    
    
    
    4.String name = "Hello World!";
    
    @NotNull: true
    @NotEmpty:true
    @NotBlank:true
    
    
    • 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

    常用的校验注解

    javax.validation.constraints.xxx
    注解 说明
    @Null 被注释的元素必须为null
    @NotNull 被注释的元素不能为null
    @AssertTrue 被注释的元素必须为true
    @AssertFalse 被注释的元素必须为false
    @Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
    @Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
    @DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
    @DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
    @Size(max,min) 被注释的元素的大小必须在指定的范围内。

     @ApiModelProperty("制造单位")
      @NotBlank(message = "makecom必须传")
      @Size(max = 30 ,message = "makecom最大长度30")
      private String makecom;
    
    • 1
    • 2
    • 3
    • 4

    @Digits(integer,fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
    @Past 被注释的元素必须是一个过去的日期
    @Future 被注释的元素必须是一个将来的日期
    @Pattern(value) 被注释的元素必须符合指定的正则表达式。
    @Email 被注释的元素必须是电子邮件地址
    @Length 被注释的字符串的大小必须在指定的范围内
    @NotEmpty 被注释的字符串必须非空
    @Range 被注释的元素必须在合适的范围内

       @ApiModelProperty("BoZhou:0是新增 1是编辑 2是删除")
        @NotNull
        @Range(min = 0, max = 2, message = "bozhou值必须在0-2之间", groups = {Insert.class, Update.class})
        private int bozhou;
    
    • 1
    • 2
    • 3
    • 4

    附 @JsonFormat

    有时使用 @JsonFormat 注解时,查到的时间可能会比数据库中的时间少八个小时,这是由于时区差引起的,JsonFormat 默认的时区是 Greenwich Time, 默认的是格林威治时间,而我们是在东八区上,所以时间会比实际我们想得到的时间少八个小时。需要在后面加上一个时区,如下示例:
    
    
    • 1
    • 2

    @JsonFormat(pattern=“yyyy-MM-dd”,timezone=“GMT+8”)
    private Date date;

    @JsonFormat(pattern=“yyyy-MM-dd”,timezone=“GMT+8”)
    private Date date;

    2.日期时间验证:

    年月日时分秒:

       /**
         * 充前检验时间
         */
        @NotNull(message = "addtime必须传")
        // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    //    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
         @Pattern(regexp = "^((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29))\\s+([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$", message = "addtime日期格式不对")
        private String addtime;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    年月日:

        @ApiModelProperty("检验日期")
        @NotBlank(message = "checkdate必须传")
    //    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    //    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    //    @Pattern(regexp = "^((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29))\\s+([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$",message = "checkdate日期格式不对")
        //    @DateTimeFormat(pattern = "yyyy-MM-dd")
        @Pattern(regexp = "^((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29))$",message = "bfdate日期格式不对")
        private String checkdate;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    二、使用步骤

    1.@RequestParam和@PathVariable的区别和使用

    /{参数值} 和 ?参数名=参数值数据

    2.java多文件下载zip

    1.java实现打包下载

    java实现打包下载
    背景:项目中下载功能单个文件正常下载多个文件或者包含文件夹打压缩包下载

    上代码

    controller

    代码如下(示例):

    @RestController
    @RequestMapping("/file")
    public class FileController {
     
     
        
        @RequestMapping(value = "/downloadFilePack", method = RequestMethod.GET)
        public void downloadFilePack(String username, String wellName,HttpServletRequest request, HttpServletResponse response) {
            if (StringUtils.isBlank(username) ) {
                throw new ResultMapException("参数为空");
            }
            FileUtil.downloadFilePack(username,wellName, request, response);
     
        }
     
     
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    FileUtile工具类

    package com.yxsd.stratum.resource.utils;
     
    import com.cloud.framework.util.DateUtils;
    import org.apache.commons.io.FileUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.apache.ibatis.executor.result.ResultMapException;
     
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.nio.charset.StandardCharsets;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import java.util.regex.Pattern;
    import java.util.stream.Stream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
     
    public class FileUtil {
     
       
       
        public static void downloadFilePack(String username, String wellName, HttpServletRequest request, HttpServletResponse response) {
            Path path =null;
            //根据参数拼的下载路径 可根据业务自己改造
            if(StringUtils.isBlank(wellName)){
              path = Paths.get(ConstantUtils.SCRIPT_BASE_DATA_PATH,username,ConstantUtils.SCRIPT_BASE_DATA_PATH_GROUP_ACCURACY_PATH);
             }else {
                wellName= wellName+".xlsx";
                path = Paths.get(ConstantUtils.SCRIPT_BASE_DATA_PATH,username,ConstantUtils.SCRIPT_BASE_DATA_PATH_GROUP_ACCURACY_PATH,wellName);
             }
            if(Files.notExists(path)){
                throw new ResultMapException("文件不存在");
            }
            List<String> list = new ArrayList<String>();
            if(Files.isDirectory(path)){
                try {
                    Stream<Path> paths = Files.list(path);
                    paths.forEach(p -> list.add(p.toString()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else {
                list.add(path.toString());
            }
     
            File file = new File(list.get(0));
            // 如果下载多个文件或下载文件夹,将文件打成压缩包进行下载
            if (list.size() > 1 || file.isDirectory()) {
                String fileZipName = DateUtils.getInstance().dateFormat(new Date()) + ".zip";
                String fileZipPath = ConstantUtils.PDF_TEMP + File.separator + fileZipName;
                zipFiles(list, fileZipPath);
                downloadF(request, response, download(fileZipPath), fileZipName);
                delete(fileZipPath);
            } else {
                // 单个文件直接下载
                downloadF(request, response, download(file.getPath()), file.getName());
            }
     
        }
     
     
        public static void downloadF(HttpServletRequest request, HttpServletResponse response, InputStream inputStream, String fileName) {
            OutputStream os = null;
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            try {
                //通过response获取的输出流,作为服务端向客户端浏览器输出内容的通道
                os = response.getOutputStream();
                // 为了提高效率使用缓冲区流
                bis = new BufferedInputStream(inputStream);
                bos = new BufferedOutputStream(os);
                // 处理下载文件名的乱码问题(根据浏览器的不同进行处理)
                if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
                    fileName = new String(fileName.getBytes("GB2312"), "ISO-8859-1");
                } else {
                    // 对文件名进行编码处理中文问题
                    fileName = java.net.URLEncoder.encode(fileName, "UTF-8");// 处理中文文件名的问题
                    fileName = new String(fileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题
                }
                response.reset();
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/x-msdownload");// 不同类型的文件对应不同的MIME类型
                response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
                int bytesRead = 0;
                byte[] buffer = new byte[4096];
                while ((bytesRead = bis.read(buffer)) != -1) {
                    bos.write(buffer, 0, bytesRead);
                    bos.flush();
                }
            } catch (Exception ex) {
                throw new RuntimeException(ex.getMessage());
            } finally {
                try {
                    if (null != bis) {
                        bis.close();
                        bis = null;
                    }
                    if (null != bos) {
                        bos.close();
                        bos = null;
                    }
                    if (null != os) {
                        os.close();
                        os = null;
                    }
                } catch (Exception ex) {
                    throw new RuntimeException(ex.getMessage());
                }
            }
        }
     
     
        public static void zipFiles(List<String> srcfiles, String zipPath) {
            File fileParent = new File(zipPath);
            if (!fileParent.getParentFile().exists() && !fileParent.isDirectory()) {
                fileParent.getParentFile().mkdirs();
            }
     
            byte[] buf = new byte[4096];
            ZipOutputStream out = null;
            try {
                // 创建zip输出流
                out = new ZipOutputStream(new FileOutputStream(fileParent));
                // 循环将源文件列表添加到zip文件中
                for (int i = 0; i < srcfiles.size(); i++) {
                    File file = new File(srcfiles.get(i));
                    FileInputStream in = new FileInputStream(file);
                    String fileName = file.getName();
                    // 将文件名作为zip的Entry存入zip文件中
                    out.putNextEntry(new ZipEntry(fileName));
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                    out.closeEntry();
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (null != out) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
     
            }
        }
     
     
        public static InputStream download(String fromPath) {
            FileInputStream inputStream = null;
            try {
                File file = new File(fromPath);
                if (file.exists()) {
                    inputStream = new FileInputStream(file);
                }
            } catch (Exception var4) {
                var4.printStackTrace();
            }
            return inputStream;
        }
     
        public static Boolean delete(String path) {
            Boolean result = false;
            try {
                File remoteFile = new File(path);
                if (!remoteFile.exists()) {
                    return false;
                }
                if (remoteFile.isFile()) {
                    result = remoteFile.delete();
                } else {
                    FileUtils.deleteDirectory(remoteFile);
                    result = true;
                }
            } catch (Exception var4) {
                var4.printStackTrace();
                result = false;
            }
     
            return result;
        }
     
    }
    
    
    • 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
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194

    测试 页面请求

    http://127.0.0.1:9091/file/downloadFilePack?username=%22test%22&wellName=%2211%22
    在这里插入图片描述
    在这里插入图片描述

    2.Java多个文件根据URL下载后打包zip导出

    Java多个文件根据URL下载后打包zip导出

    该示例框架为Spring Boot,根据Url把多个文件下载到指定的文件夹目录,然后再将文件夹目录打包成zip导出,有个简单的导出html页面,点击导出按钮下载zip

    所需jar包commons-io

    service层

    package com.test.service;
     
    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
     
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
     
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
     
    public class Test {
    	private static Logger logger = LoggerFactory.getLogger(Test.class);
    	/**
    	 * 需要压缩的文件夹
    	 */
    	private final static String downloadDir = "download";
    	/**
    	 * 打包后的文件夹
    	 */
    	private final static String downloadZip = "downloadZip";
    	
    	/**
    	 * 通过图片url下载图片到指定文件夹
    	 * @param downloadUrl	图片url
    	 */
    	public void downloadFile(String downloadUrl) {
    		InputStream inputStream = null;
    		OutputStream outputStream = null;
    		try {
    			//获取连接
    	        URL url=new URL(downloadUrl);
    	        HttpURLConnection connection=(HttpURLConnection)url.openConnection();
    	        connection.setConnectTimeout(3*1000);
    	        //设置请求头
    	        connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36");
    	        //获取输入流
    	        inputStream=connection.getInputStream();
    	        
    	        File fileDir=new File(downloadDir);
    			if(!fileDir.exists()){//如果文件夹不存在
    				fileDir.mkdir();//创建文件夹
    			}
    			
    	        //截取文件名称,可以把 / 换成需要的规则
    	        String filePath = downloadDir+"/" + downloadUrl.substring(downloadUrl.lastIndexOf("/"));
    	        File file = new File(filePath);
    			file.createNewFile();//创建文件,存在覆盖
    			
    			outputStream = new FileOutputStream(file);
    			int len = 0;
    			byte[] buf = new byte[1024];
    			while ((len = inputStream.read(buf, 0, 1024)) != -1) {
    				outputStream.write(buf, 0, len);
    			}
    			outputStream.flush();
    		} catch (Exception e) {
    			logger.error("文件下载出错:" + e);
    		} finally {
    			try {
    				if (inputStream != null) {
    					inputStream.close();
    				}
    				if (outputStream != null) {
    					outputStream.close();
    				}
    			} catch (IOException e) {
    				logger.error("关闭流出错:" + e);
    			}
    		}
    	}
    	
    	
        /**
         * 下载压缩包
         */
    	public void downloadZip(HttpServletRequest request,HttpServletResponse res) throws IOException {
    		OutputStream out = null;
    		File zip = null;
    		try{
    	    	//多个文件进行压缩,批量打包下载文件 
    		    //创建压缩文件需要的空的zip包  
    		    String zipName = "测试压缩包.zip";
    		    String zipFilePath = downloadZip+File.separator+zipName;  
    	
    		    File fileDir=new File(downloadZip);
    			if(!fileDir.exists()){//如果文件夹不存在
    				fileDir.mkdir();//创建文件夹
    			}
    			
    		    //压缩文件
    		    zip = new File(zipFilePath);  
    	        zip.createNewFile();//创建文件,存在覆盖
    		    
    		    //创建zip文件输出流  
    	        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zip));
    		    this.zipFile(downloadDir, zos);
    		    zos.close();
    		    
    		    //将打包后的文件写到客户端,输出的方法同上,使用缓冲流输出  
    		    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipFilePath));  
    		    byte[] buff = new byte[bis.available()];  
    		    bis.read(buff);
    		    bis.close();
    		    
    		    //IO流实现下载的功能  
    		    res.setCharacterEncoding("UTF-8"); //设置编码字符
    		    res.setContentType("application/octet-stream;charset=UTF-8"); //设置下载内容类型application/octet-stream(二进制流,未知文件类型);
    		    
    		    //防止文件名乱码
    		    String userAgent = request.getHeader("USER-AGENT");
                if (userAgent.contains("Firefox") || userAgent.contains("firefox")) {//火狐浏览器
                	zipName = new String(zipName.getBytes(), "ISO8859-1");
                } else {
                	zipName = URLEncoder.encode(zipName, "UTF-8");//其他浏览器
                }
    		    
                res.setHeader("Content-disposition", "attachment;filename="+zipName);//设置下载的压缩文件名称
    		    out = res.getOutputStream();   //创建页面返回方式为输出流,会自动弹出下载框   
    		    out.write(buff);//输出数据文件
    		    
    	    }catch(Exception e) {
    	    	logger.error("压缩包下载出错:" + e);
    		}finally {
    			if(out != null){
    				out.flush();//释放缓存
    				out.close();//关闭输出流
    			}
    			
    			//下载完后删除文件夹和压缩包
    //			File fileDir = new File(downloadDir);
    //			FileUtils.deleteDirectory(fileDir);
    //			
    //			if(zip != null){
    //				zip.delete();
    //			}
    		}
    	}
    	
    	/**
    	 * 压缩文件
    	 * @param filePath	需要压缩的文件夹
    	 * @param zos	zip文件输出流 
    	 */
    	private void zipFile(String filePath,ZipOutputStream zos) throws IOException {
            File inputFile = new File(filePath);  //根据文件路径创建文件  
            if(inputFile.exists()) { //判断文件是否存在  
                if (inputFile.isFile()) {  //判断是否属于文件,还是文件夹  
                    //创建输入流读取文件  
                    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputFile));  
     
                    //将文件写入zip内,即将文件进行打包  
                    zos.putNextEntry(new ZipEntry(inputFile.getName()));  
     
                    //写入文件的方法,同上                  
                    int size = 0;  
                    byte[] buffer = new byte[1024];  //设置读取数据缓存大小
                    while ((size = bis.read(buffer)) > 0) {  
                    	zos.write(buffer, 0, size);  
                    }  
                    //关闭输入输出流  
                    zos.closeEntry();  
                    bis.close(); 
                    
                } else {  //如果是文件夹,则使用穷举的方法获取文件,写入zip  
                    try {  
                        File[] files = inputFile.listFiles();  
                        for (File fileTem:files) {  
                        	zipFile(fileTem.toString(),zos);
                        }  
                    } catch (Exception e) {  
                    	logger.error("压缩文件出错:" + e);
                    }  
                }  
            }  
    	} 
    }
    
    • 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
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187

    controller层

    package com.test.controller;
     
    import java.io.IOException;
     
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
     
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
     
    import com.test.service.Test;
     
    @RestController
    @RequestMapping("/test")
    public class TestController {
     
    	@Autowired
    	private HttpServletRequest request;
    	@Autowired
    	private HttpServletResponse response;
    	
    	@RequestMapping(value = "dc", method = RequestMethod.GET)
    	public void syncAll() {
    		try {
    			//模拟从数据库查出多张图片路径
    			String[] urlArr = new String[]{
    					"https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2069658043,3652854281&fm=26&gp=0.jpg",
    					"https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1569705026,760128093&fm=26&gp=0.jpg"
    					};
    			Test test = new Test();
    			for (String url : urlArr) {
    				//下载查出的图片
    				test.downloadFile(url);
    			}
    			//把下载的图片文件夹压缩
    			test.downloadZip(request, response);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
     
    }
    
    • 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

    maven

    <dependency>
    			<groupId>org.apache.commons</groupId>
    			<artifactId>commons-io</artifactId>
    			<version>1.3.2</version>
    		</dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    html测试导出页面

    <!DOCTYPE html>
    <html>
      <head>
        <title>测试文件压缩导出</title>
    	
        <meta name="keywords" content="keyword1,keyword2,keyword3">
        <meta name="description" content="this is my page">
        <meta name="content-type" content="text/html; charset=UTF-8">
      </head>
      
      <body style="font-size: 3em;">
        	<a href="http://localhost:8080/test/dc">导出</a>
      </body>
    </html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    源码下载:https://download.csdn.net/download/u011974797/16685844

    分割线--------------------------------------------------------------------------------------------------------------------------

    扩展:前面的是压缩目录下的所有文件,如果需要压缩目录下的子目录和文件,可以参考下面的代码
    ————————————————
    版权声明:本文为CSDN博主「谢小涛」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/u011974797/article/details/115749299

    package com.test.service;
     
    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
     
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
     
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
     
    /**
     * 压缩子目录和文件
     */
    public class FileTest {
    	private static Logger logger = LoggerFactory.getLogger(FileTest.class);
    	/**
    	 * 需要压缩的文件夹
    	 */
    	private final static String downloadDir = "download";
    	/**
    	 * 打包后的文件夹
    	 */
    	private final static String downloadZip = "downloadZip";
    	
    	/**
    	 * 通过图片url下载图片到指定文件夹
    	 * @param downloadUrl	图片url
    	 */
    	public void downloadFile(String downloadUrl, String fileName) {
    		InputStream inputStream = null;
    		OutputStream outputStream = null;
    		try {
    			//获取连接
    	        URL url=new URL(downloadUrl);
    	        HttpURLConnection connection=(HttpURLConnection)url.openConnection();
    	        connection.setConnectTimeout(3*1000);
    	        //设置请求头
    	        connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36");
    	        //获取输入流
    	        inputStream=connection.getInputStream();
    	        
    	        File fileDir=new File(downloadDir);
    			if(!fileDir.exists()){//如果文件夹不存在
    				fileDir.mkdir();//创建文件夹
    			}
    			
    	        //截取文件名称,可以把 / 换成需要的规则
    	        String filePath = downloadDir+"/" + fileName+downloadUrl.substring(downloadUrl.lastIndexOf("."));
    	        File file = new File(filePath);
    			file.createNewFile();//创建文件,存在覆盖
    			
    			outputStream = new FileOutputStream(file);
    			int len = 0;
    			byte[] buf = new byte[1024];
    			while ((len = inputStream.read(buf, 0, 1024)) != -1) {
    				outputStream.write(buf, 0, len);
    			}
    			outputStream.flush();
    		} catch (Exception e) {
    			logger.error("文件下载出错:" + e);
    		} finally {
    			try {
    				if (inputStream != null) {
    					inputStream.close();
    				}
    				if (outputStream != null) {
    					outputStream.close();
    				}
    			} catch (IOException e) {
    				logger.error("关闭流出错:" + e);
    			}
    		}
    	}
    	
    	
        /**
         * 下载压缩包
         */
    	public void downloadZip(HttpServletRequest request,HttpServletResponse res) throws IOException {
    		OutputStream out = null;
    		File zip = null;
    		try{
    	    	//多个文件进行压缩,批量打包下载文件 
    		    //创建压缩文件需要的空的zip包  
    		    String zipName = "测试压缩包.zip";
    		    String zipFilePath = downloadZip+File.separator+zipName;  
    	
    		    File fileDir=new File(downloadZip);
    			if(!fileDir.exists()){//如果文件夹不存在
    				fileDir.mkdir();//创建文件夹
    			}
    			
    		    //压缩文件
    		    zip = new File(zipFilePath);  
    	        zip.createNewFile();//创建文件,存在覆盖
    		    
    		    //创建zip文件输出流  
    	        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zip));
    	        File inputFile = new File(downloadDir);  //根据文件路径创建文件  
    		    File[] fileLists = inputFile.listFiles(); // 如果是目录,获取该目录下的内容集合
     
    		    //压缩这个目录下所有内容,包括文件夹和文件,只压缩下级目录,下下级需要自己扩展
                for (int i = 0; i < fileLists.length; i++) { // 循环遍历这个集合内容
                    if (fileLists[i].isDirectory()) {    //判断元素是不是一个目录
                    	//如果存在目录,压缩子目录
                    	this.zipFile(fileLists[i], zos, fileLists[i].getName());
                    }else{
                    	//压缩文件,不需要目录名称传空
                    	this.zipFile(fileLists[i], zos, "");
                    }
                }
    		    
    		    zos.close();
                
    		    //将打包后的文件写到客户端,输出的方法同上,使用缓冲流输出  
    		    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipFilePath));  
    		    byte[] buff = new byte[bis.available()];  
    		    bis.read(buff);
    		    bis.close();
    		    
    		    //IO流实现下载的功能  
    		    res.setCharacterEncoding("UTF-8"); //设置编码字符
    		    res.setContentType("application/octet-stream;charset=UTF-8"); //设置下载内容类型application/octet-stream(二进制流,未知文件类型);
    		    
    		    //防止文件名乱码
    		    String userAgent = request.getHeader("USER-AGENT");
                if (userAgent.contains("Firefox") || userAgent.contains("firefox")) {//火狐浏览器
                	zipName = new String(zipName.getBytes(), "ISO8859-1");
                } else {
                	zipName = URLEncoder.encode(zipName, "UTF-8");//其他浏览器
                }
    		    
                res.setHeader("Content-disposition", "attachment;filename="+zipName);//设置下载的压缩文件名称
    		    out = res.getOutputStream();   //创建页面返回方式为输出流,会自动弹出下载框   
    		    out.write(buff);//输出数据文件
    		    
    	    }catch(Exception e) {
    	    	logger.error("压缩包下载出错:" + e);
    		}finally {
    			if(out != null){
    				out.flush();//释放缓存
    				out.close();//关闭输出流
    			}
    			
    			//下载完后删除文件夹和压缩包
    //			File fileDir = new File(downloadDir);
    //			FileUtils.deleteDirectory(fileDir);
    //			
    //			if(zip != null){
    //				zip.delete();
    //			}
    		}
    	}
    	
    	/**
    	 * 压缩文件
    	 * @param filePath	需要压缩的文件夹
    	 * @param zos	zip文件输出流 
    	 * @param folderName	文件夹名称,用于压缩子目录
    	 */
    	private void zipFile(File inputFile,ZipOutputStream zos,String folderName) throws IOException {
            if(inputFile.exists()) { //判断文件是否存在  
                if (inputFile.isFile()) {  //判断是否属于文件,还是文件夹  
                    //创建输入流读取文件  
                    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputFile));  
     
                    //将文件写入zip内,即将文件进行打包  
                    zos.putNextEntry(new ZipEntry(folderName+inputFile.getName()));  
     
                    //写入文件的方法,同上                  
                    int size = 0;  
                    byte[] buffer = new byte[1024];  //设置读取数据缓存大小
                    while ((size = bis.read(buffer)) > 0) {  
                    	zos.write(buffer, 0, size);  
                    }  
                    //关闭输入输出流  
                    zos.closeEntry();  
                    bis.close(); 
                    
                } else {  //如果是文件夹,则使用穷举的方法获取文件,写入zip  
                    try {  
                        File[] files = inputFile.listFiles();  
                        for (File fileTem:files) {  
                        	zipFile(fileTem, zos, folderName + "/");
                        }  
                    } catch (Exception e) {  
                    	logger.error("压缩文件出错:" + e);
                    }  
                }  
            }  
    	} 
    }
    
    • 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
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203

    关键代码部分

    //将文件写入zip内,即将文件进行打包  
    zos.putNextEntry(new ZipEntry(folderName+inputFile.getName()));  
    
    • 1
    • 2

    前面加了个folderName文件夹名称,比如之前是:图片.jpg,那么 图片.jpg 就会压缩到根目录下,如果加上文件夹名称:test/图片.jpg,那么 图片.jpg 就会压缩到子目录test下面

    如果需要压缩一级、二级、三级所有层级目录,那么需要先遍历出来,然后同理压缩即可
    ————————————————
    版权声明:本文为CSDN博主「谢小涛」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/u011974797/article/details/115749299

  • 相关阅读:
    【向题看齐】408之数据结构DS概念记忆总结
    网易企业邮箱斩获双料奖项!产品实力与客户口碑双丰收!【公司邮箱怎么申请】
    vue PasswordStrength密码强度组件
    彻底掌握Makefile(三)
    3. 数组+【矩阵压缩存储】:对称、三角、三对角、稀疏矩阵
    SpringBoot入门
    String字符串的常用方法
    同步代码块、同步方法解决数据安全问题、线程安全的类及Lock锁
    CSAPP题目 3.59
    R-CNN 详解
  • 原文地址:https://blog.csdn.net/gys9895/article/details/133740984