java springMVC数据的打包下载

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xyzhanhh/article/details/54287140

前几天做了一个上传下载功能,开始下载做的很顺利,然而上传的时候遇到很多难题,好在都已经解决。

虽然这个下载功能做完了,但我还不是很满意,因为我创建文件与压缩包都是在服务器磁盘中操作的,原本想直接在内存中操作,

但查了半天,还是不知道该怎么做,如果有看到这个文章并正好知道的朋友麻烦告诉或指正一下。

好了,上代码:


//1、获取数据,根据数据(树形)创建目录与目录下的文件夹。


//2、说明文件在指定目录下创建(xml文件,说明导出文件结构与各结构文件名称)

/**
     * 创建xml文件
     * @param path
     * 创建xml文件路径
     * @param template
     * 文件内容
     * @throws IOException
     */
   @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void createXML(File xmlFile,List<Map<String,Object>> template,Element parentRoot) throws IOException{
        if(parentRoot ==null){
               parentRoot = DocumentHelper.createElement("root");  
           }
           for(Map<String, Object> chilids : template){
               Iterator entries = chilids.entrySet().iterator();
               if(chilids.get("id")!=null && chilids.get("type")!=null){
                   Element element = parentRoot.addElement("id");
                   while (entries.hasNext()) {  
                       Map.Entry entry = (Map.Entry) entries.next();
                       if(entry.getKey().equals("childs")){
                           List<Map<String,Object>> chilidMap = (List<Map<String, Object>>) chilids.get("childs");
                           if(chilidMap!=null && chilidMap.size()>0){
                            Element element1 = element.addElement("childs");
                            createXML(xmlFile,chilidMap,element1);
                        }
                       }else{
                           element.addElement(entry.getKey()+"").addText(entry.getValue()==null?"":entry.getValue()+"");
                       }
                }
               }else{
                   while (entries.hasNext()) {  
                       Map.Entry entry = (Map.Entry) entries.next();
                    parentRoot.addElement(entry.getKey()+"").addText(entry.getValue()+"");
                }  
               }
            
           }
        //把生成的xml文档存放在硬盘上  
        OutputFormat format = new OutputFormat();  
       // format.setNewlines(true); //是否换行  
        format.setEncoding("UTF-8");//设置编码格式  
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(xmlFile),format);  
        xmlWriter.write(parentRoot);  
        xmlWriter.close();
   }


//3、复制所用到的jar包到指定目录

    /**
     * 将源文件复制到目标文件中
     * @param jarPath
     * 源文件路径
     * @param sourcePath
     * 目标文件路径
     */
    @SuppressWarnings("unused")
    public void copyFile(String sourcePath, String destPath) {
        int bytesum = 0;
        int byteread = 0;
        InputStream inStream = null;
        FileOutputStream fs = null;
        File sourceFile = new File(sourcePath);
        File destFile = new File(destPath);
        if(!destFile.exists()){
            try {
                destFile.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try{
            //FileUtils.copyDirectory(sourceFile, to);
            if (sourceFile.exists()) { //文件存在时
                inStream = new FileInputStream(sourcePath); //读入原文件
                fs = new FileOutputStream(destFile);
                byte[] buffer = new byte[1444];
                while ( (byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread; //字节数 文件大小
                fs.write(buffer, 0, byteread);
                }
            }
        }catch (Exception e) {
            e.printStackTrace();

        }finally{
            if(inStream != null){
                try {
                    inStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(fs != null){
                try {
                    fs.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

//4、压缩文件

    /**
     * @decription 将源目录下的文件压缩到指定压缩文件中
     * @param resourcesPath
     * @param targetPath
     * @throws IOException
     * @throws Exception
     */
    public static synchronized void compressedFile(String sourcesPath,String exportPath,String exportFileName) throws IOException{  
        File sourcesFile = new File(sourcesPath);     //源文件  
        File targetFile = new File(exportPath);           //目的  
        //如果目的路径不存在,则新建  
        if(!targetFile.exists()){       
            targetFile.mkdirs();    
        }
        File exportFile = new File(exportPath+separator+exportFileName);           //目的  
        //如果目的路径不存在,则新建  
        if(!exportFile.exists()){       
            exportFile.createNewFile();    
        }
        FileOutputStream outputStream =null;
        ZipOutputStream out = null;
        try {
            outputStream = new FileOutputStream(exportFile);
            out = new ZipOutputStream(outputStream);  
            out.setEncoding("UTF-8");
            createCompressedFile(out, sourcesFile, "");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream !=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        System.gc();
    }  
    /**
     * @decription 生成压缩文件。
     *     如果是文件夹,则使用递归,进行文件遍历、压缩
     *     如果是文件,直接压缩
     * @param out 输出流
     * @param file 目标文件
     * @param dir 文件名称
     * @throws Exception
     */
    public static void createCompressedFile(ZipOutputStream out,File file,String dir){  
        //如果当前的是文件夹,则进行进一步处理  
        if(file.isDirectory()){  
            //得到文件列表信息  
            File[] files = file.listFiles();  
            //将文件夹添加到下一级打包目录  
            try {
                out.putNextEntry(new ZipEntry(dir+separator));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  
            dir = dir.length() == 0 ? "" : dir +separator;  
            //循环将文件夹中的文件打包  
            for(int i = 0 ; i < files.length ; i++){  
                createCompressedFile(out, files[i], dir + files[i].getName());         //递归处理  
            }  
        }else{   //当前的是文件,打包处理
            //文件输入流  
             FileInputStream fis = null;
            try {
                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);  
                }  
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }   
        }  
    }
//5、下载

OutputStream os = null;
        FileInputStream in = null;
        try {
             File zipFile = new File(exportFilePath+separator+exportFileName);
             response.setContentType("application/octet-stream");
            String zipName = URLEncoder.encode(zipFile.getName(), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="
                    + zipName);
            os = response.getOutputStream();
            in = new FileInputStream(zipFile);
            IOUtils.copy(in, os);
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //导出后删除打包文件所在文件夹
            FileUtils.deleteDirectory(exportFilePath);
        }

猜你喜欢

转载自blog.csdn.net/xyzhanhh/article/details/54287140