FileUtil.java 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package com.mall.util;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import java.io.BufferedInputStream;
  5. import java.io.BufferedOutputStream;
  6. import java.io.File;
  7. import java.io.FileInputStream;
  8. import java.net.URLEncoder;
  9. public class FileUtil {
  10. private static final String CONTENT_TYPE = "application/x-msdownload;charset=UTF-8";
  11. /*
  12. * 下载文件
  13. */
  14. public void doDownloadFile(String filePath, String filename, HttpServletRequest request, HttpServletResponse response) throws Exception {
  15. BufferedInputStream bis = null;
  16. BufferedOutputStream bos = null;
  17. try {
  18. long fileLength = new File(filePath).length();
  19. filename = URLEncoder.encode(filename, "UTF-8");
  20. response.reset();
  21. response.setContentType(CONTENT_TYPE);
  22. response.setHeader("Content-Length", String.valueOf(fileLength));
  23. response.addHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
  24. bis = new BufferedInputStream(new FileInputStream(filePath));
  25. bos = new BufferedOutputStream(response.getOutputStream());
  26. byte[] buff = new byte[2048];
  27. int bytesRead;
  28. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
  29. bos.write(buff, 0, bytesRead);
  30. }
  31. } catch (Exception e) {
  32. e.printStackTrace();
  33. } finally {
  34. if (bis != null)
  35. bis.close();
  36. if (bos != null)
  37. bos.close();
  38. }
  39. }
  40. //删除目录底下的文件
  41. public void doRemoveFile(String filepath){
  42. try{
  43. File file=new File(filepath);
  44. if(file.exists()){
  45. boolean b=file.delete();
  46. }
  47. }catch(Exception e){
  48. e.printStackTrace();
  49. }
  50. }
  51. }