Java file download code examples (single file download and multi file package download)

Time:2021-2-20

This article mainly introduces the java file download code examples (single file download and multi file package download). The example code is introduced in great detail, which has a certain reference learning value for everyone’s study or work. Friends who need it can refer to it

Recently, the project needs to write a file to download the relevant code, here to submit and record the relevant code module, the writing is not very good, later optimize the relevant code, there are good suggestions, can leave a message, thank you.

1) Single file download

public String oneFileDownload(HttpServletRequest request,HttpServletResponse response){
    //According to the requirement, communicate with the requirement and download the file transfer parameters
    //Currently, the demo file name is named by the hashcode value + suffix of the file, which can be the unique ID of the file by default
    String fileName = request.getParameter("fileName");
    if(StringUtils.isBlank(fileName)){
      Return "the file name is empty.";
    }
    String filePath =  request.getSession ().getServletContext().getRealPath("/convert")+ File.separator +Currently, the file is in this folder by default, and subsequent changes need to be modified
    File downloadFile = new File(filePath);
    if(downloadFile.exists()){
      OutputStream out = null;
      FileInputStream fis = null;
      BufferedInputStream bis = null;
      try {
        if(downloadFile.isDirectory()){
          Return "the path error only points to the folder.";
        }
        out =  response.getOutputStream (); // create a page, return to the output stream and pop up the download box
        fis = new FileInputStream(downloadFile);
        bis = new BufferedInputStream(fis);
        response.setContentType ("application / PDF; charset = UTF-8"); // set encoding characters
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        byte[] bt = new byte[2048];
        int size = 0;
        while((size=bis.read(bt)) != -1){
          out.write(bt, 0, size);
        }

      } catch (Exception e) {
        e.printStackTrace();
      }finally {
        try {
          //Close the flow
          out.flush();
          if(out != null){
            out.close();
          }
          if(bis != null){
            bis.close();
          }
          if(fis != null){
            fis.close();
          }
        } catch (Exception e2) {
          e2.printStackTrace();
        }

      }
      Return "download succeeded";
    }else{
      
      Return "the file does not exist! ";  
    }

  }

2) Multi file package download

a) Download the files under the specified folder, if nested folder also supports (but the file name needs to be unique)

public String zipDownload(HttpServletRequest request,HttpServletResponse response) throws IOException{
    
    String sourceFilePath =  request.getSession (). Getservletcontext (). Getrealpath ("/ convert"); // file path
    String destinFilePath = request.getSession().getServletContext().getRealPath("/fileZip");
    String fileName = FileUtil.zipFiles(sourceFilePath, destinFilePath);
    File file = new File(destinFilePath+File.separator+fileName);
    response.setHeader("Content-disposition", "attachment;filename=" + fileName);
    if(file.exists()){
      FileInputStream fis = null;
      BufferedInputStream bis = null;
      OutputStream out = response.getOutputStream();
      try {
        fis = new FileInputStream(file);
        bis = new BufferedInputStream(fis);
        byte[] bufs = new byte[1024 * 10];
        int read = 0;
        while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
          out.write(bufs, 0, read);
        }
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      }finally {
        if(bis != null){
          bis.close();
        }
        if(out!=null){
          out.close();
        }
        File zipFile = new File(destinFilePath+File.separator+fileName);
        if(zipFile.exists()){
          zipFile.delete();
        }
      }
    }else{
      Return "file compression failed.";
    }
    Return "download succeeded";
  }

b) Download all files in the specified folder, support tree structure

public String zipDownloadRelativePath(HttpServletRequest request,HttpServletResponse response) {
    String MSG = "; // download prompt
    String root =  request.getSession (). Getservletcontext (). Getrealpath ("/ convert"); // file path
    Vector < File > filevector = new vector < File > (); // define container load file
    File file = new File(root);
    File [] subFile = file.listFiles();
    //Judge the nature of the document and take the document
    for(int i = 0; i<subFile.length; i++){
      If (! Subfile [i]. Isdirectory()) {// is not a folder and is not empty
        fileVector.add (subfile [i]); // load the file
      }Else {// is a folder. Recursively traverse the files in the folder again
        File [] files = subFile[i].listFiles();
        Vector v = FileUtil.getPathAllFiles(subFile[i],new Vector<File>());
        fileVector.addAll (v) ; // load the iterated file into the container
      }
    }
    //Set file download name
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    String fileName = dateFormat.format(new Date())+".zip";
    response.setHeader ("content disposition", "attachment; file name =" + file name); // transcoding is required if there is Chinese
    //Defining related flows
    //For browser download response
    OutputStream out = null;
    //Used to read compressed files
    Bufferedinputstream bis = null; // better performance with caching
    //Used to compress files
    ZipOutputStream zos = null;
    //Create an empty zip file
    String zipBasePath = request.getSession().getServletContext().getRealPath("/fileZip");
    String zipFilePath = zipBasePath+File.separator+fileName;
    File zipFile = new File(zipFilePath);
    try {
      if(! zipFile.exists ()) {// does not exist. Create a new one
        zipFile.createNewFile();
      }
      out = response.getOutputStream();
      //Create file output stream
      zos = new ZipOutputStream(new FileOutputStream(zipFile));
      //Loop files, one by one, compressed in sequence
      for(int i = 0;i< fileVector.size();i++){
        System.out.println ( fileVector.get (i) . getname() + "size is:+ fileVector.get (i).length());
        FileUtil.zipFileFun(fileVector.get(i),root,zos);
      }
      //After the compression is completed, you must close the file here, otherwise there will be problems downloading the file
      if(zos != null){
        zos.closeEntry();
        zos.close();
        }
      byte[] bt = new byte[10*1024];
      int size = 0;
      bis = new BufferedInputStream(new FileInputStream(zipFilePath),10*1024);
      while((size= bis.read (BT, 0,10 * 1024))! = - 1) {// not finished
        out.write(bt,0,size);
      }
      
    } catch (Exception e) {
      e.printStackTrace();
    }Finally {// close related flow
      try {
        //Avoid failure to close in case of exception
        if(zos != null){
          zos.closeEntry();
          zos.close();
          }
        
        if(bis != null){
          bis.close();
        }
        
        if(out != null){
          out.close();
        }
        if(zipFile.exists()){
          zipFile.delete (); // delete
        }
      } catch (Exception e2) {
        System.out.println "Error closing stream! ");
      }

    }
    Return "download succeeded";
  }

Download auxiliary tools

package com.hhwy.fileview.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;




public class FileUtil {
  /**
   *Compress the file containing folder under a file path into a file
   * @param file
   *Relative address of @ param rootpath
   * @param zipoutputStream
   */
  public static void zipFileFun(File file,String rootPath,ZipOutputStream zipoutputStream){
    if( file.exists ()) {// the file is valid only if it exists
      if(file.isFile()){
        //Define related operation flow
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
          //Set up folder
          String relativeFilePath = file.getPath().replace(rootPath+File.separator, "");
          //Create input stream read file
          fis = new FileInputStream(file);
          bis = new BufferedInputStream(fis,10*1024);
          //Load the file into zip and start packing
          ZipEntry zipEntry;
          if(!relativeFilePath.contains("\")){
            zipEntry = new ZipEntry( file.getName ()); // the value here can't be repeated and must be unique, otherwise the file with the same name will report an error
          }else{
            Zipentry = new zipentry (relative filepath); // the value here can't be repeated and must be unique, otherwise the file with the same name will report an error
          }
          zipoutputStream.putNextEntry(zipEntry);
          //Start writing file
          byte[] b = new byte[10*1024];
          int size = 0;
          while((size= bis.read (B, 0,10 * 1024))! = - 1) {// not finished
            zipoutputStream.write(b,0,size);
          }
        } catch (Exception e) {
          e.printStackTrace();
        }finally {
          try {
            //Close the related flow operation after reading
            if(bis != null){
              bis.close();
            }
            if(fis != null){
              fis.close();
            }
          } catch (Exception e2) {
            System.out.println "Stream close error! ");
          }
        }
      }
//Else {// if it is a folder
//        try {
//          File [] files =  file.listFiles (); // get all the files in the folder
//          for(File f : files){
//            zipFileFun(f,rootPath, zipoutputStream);
//          }
//        } catch (Exception e) {
//          e.printStackTrace();
//        }
//        
//      }
    }
  }
  
  /*
   *Get all files in a folder
   */
  public static Vector<File> getPathAllFiles(File file,Vector<File> vector){
    if( file.isFile ()) {// if it is a file, load it directly
      System.out.println (file in iterated function)+ file.getName () + "size is:+ file.length ());
      vector.add(file);
    }Else {// folder
      File[] files = file.listFiles();
      For (file f: files) {// recursion
        if(f.isDirectory()){
          getPathAllFiles(f,vector);
        }else{
          System.out.println ("file in iterated function" + f.getname() + "size: + f.length());
          vector.add(f);
        }
      }
    }
    return vector;
  }
  
  /**
   *Compress files to specified folder
   *@ param sourcefilepath source address
   *@ param destinfilepath destination address
   */
  public static String zipFiles(String sourceFilePath,String destinFilePath){
    File sourceFile = new File(sourceFilePath);
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    FileOutputStream fos = null;
    ZipOutputStream zos = null;
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    String fileName = dateFormat.format(new Date())+".zip";
    String zipFilePath = destinFilePath+File.separator+fileName;
    if (sourceFile.exists() == false) {
      System.out.println ("file directory to be compressed: + sourcefilepath +" does not exist. ");
    } else {
      try {
        File zipFile = new File(zipFilePath);
        if (zipFile.exists()) {
          System.out.println (zipfilepath + "directory with the name of" + filename + ". Zip" + "package file.");
        } else {
          File[] sourceFiles = sourceFile.listFiles();
          if (null == sourceFiles || sourceFiles.length < 1) {
            System.out.println ("directory of files to be compressed: + sourcefilepath +" there are no files in it, so there is no need to compress. ");
          } else {
            //Read all the files under Sourcefile
            Vector<File> vector = FileUtil.getPathAllFiles(sourceFile, new Vector<File>()); 
            fos = new FileOutputStream(zipFile);
            zos = new ZipOutputStream(new BufferedOutputStream(fos));
            byte[] bufs = new byte[1024 * 10];
            
            for (int i = 0; i < vector.size(); i++) {
              //Create a zip entity and add it to the package
              ZipEntry zipEntry = new ZipEntry( vector.get (i) . getname()); // the file name cannot be duplicated, otherwise an error will be reported
              zos.putNextEntry(zipEntry);
              //Read the file to be compressed and write it into the compressed package
              fis = new FileInputStream(vector.get(i));
              bis = new BufferedInputStream(fis, 1024 * 10);
              int read = 0;
              while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
                zos.write(bufs, 0, read);
              }
            }
          }
        }
      } catch (FileNotFoundException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
      } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
      } finally {
        //Close the flow
        try {
          if (null != bis)
            bis.close();
          if (null != zos)
            zos.closeEntry();
            zos.close();
        } catch (IOException e) {
          e.printStackTrace();
          throw new RuntimeException(e);
        }
      }
    }
    return fileName;
  }
  
}

All the self tests here can be used normally, and the code quality is not high

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.