File工具类

浅浅的花香味﹌ 2023-09-30 11:26 107阅读 0赞
  1. import sun.misc.BASE64Encoder;
  2. import javax.servlet.ServletOutputStream;
  3. import javax.servlet.http.HttpServletRequest;
  4. import javax.servlet.http.HttpServletResponse;
  5. import java.io.*;
  6. import java.net.URLEncoder;
  7. import java.util.List;
  8. import java.util.zip.ZipEntry;
  9. import java.util.zip.ZipOutputStream;
  10. public class FileDownloadUtils {
  11. /**
  12. * 创建文件夹;
  13. *
  14. * @param path 路径
  15. */
  16. public static void createFile(String path) {
  17. File file = new File(path);
  18. //判断文件是否存在;
  19. if (!file.exists()) {
  20. //创建文件;
  21. file.mkdirs();
  22. }
  23. }
  24. /**
  25. * 将多个文件打包成fileName名称的zip文件,并存放到zipFilePath路径下
  26. * (把指定文件夹下的所有文件目录和文件都压缩到指定文件夹下)
  27. *
  28. * @param zipFilePath :压缩后存放路径
  29. * @param fileName :压缩后文件的名称
  30. * @return boolean
  31. */
  32. public static boolean fileToZip(List<File> files, String zipFilePath, String fileName) {
  33. boolean flag = false;
  34. FileInputStream fis;
  35. BufferedInputStream bis = null;
  36. FileOutputStream fos;
  37. ZipOutputStream zos = null;
  38. try {
  39. File zipFile = new File(zipFilePath + "/" + fileName + ".zip");
  40. if (zipFile.exists()) {
  41. System.out.println(zipFilePath + "目录下存在名字为:" + fileName
  42. + ".zip" + "的打包文件.");
  43. } else {
  44. if (!zipFile.exists()) {
  45. zipFile.getParentFile().mkdirs();
  46. }
  47. fos = new FileOutputStream(zipFile);
  48. zos = new ZipOutputStream(new BufferedOutputStream(fos));
  49. byte[] bufs = new byte[1024 * 1024];
  50. for (int i = 0; i < files.size(); i++) {
  51. try {
  52. //创建ZIP实体,并添加进压缩包
  53. ZipEntry zipEntry = new ZipEntry(String.valueOf(files.get(i)));
  54. zos.putNextEntry(zipEntry);
  55. // 读取待压缩的文件并写进压缩包里
  56. fis = new FileInputStream(files.get(i));
  57. bis = new BufferedInputStream(fis, 1024 * 1024);
  58. int read;
  59. while ((read = bis.read(bufs, 0, 1024 * 1024)) != -1) {
  60. zos.write(bufs, 0, read);
  61. }
  62. } catch (Exception e) {
  63. //logger.error("文件读取处理有误");
  64. e.printStackTrace();
  65. }
  66. }
  67. flag = true;
  68. }
  69. } catch (IOException e) {
  70. e.printStackTrace();
  71. throw new RuntimeException(e);
  72. } finally {
  73. // 关闭流
  74. try {
  75. if (null != bis)
  76. bis.close();
  77. if (null != zos)
  78. zos.close();
  79. } catch (IOException e) {
  80. e.printStackTrace();
  81. throw new RuntimeException(e);
  82. }
  83. }
  84. return flag;
  85. }
  86. /**
  87. * 将批量文件打包下载成zip
  88. *
  89. * @param request 请求
  90. * @param response 返回
  91. * @param zipName 下载的zip名
  92. * @param files 要打包的批量文件
  93. * @param zipPath 生成的zip路径
  94. * @throws Exception 异常
  95. */
  96. public static void downloadZip(HttpServletRequest request, HttpServletResponse response, String zipName, List<File> files, String zipPath) throws Exception {
  97. File[] srcfile = new File[files.size()];
  98. File zip = new File(zipPath);
  99. for (int i = 0; i < files.size(); i++) {
  100. srcfile[i] = files.get(i);
  101. }
  102. //生成.zip文件;
  103. FileInputStream inStream = null;
  104. ServletOutputStream os = null;
  105. try {
  106. //设置下载zip的头信息
  107. FileDownloadUtils.setZipDownLoadHeadInfo(response, request, zipName);
  108. os = response.getOutputStream();
  109. //压缩文件
  110. FileDownloadUtils.ZipFiles(srcfile, zip);
  111. inStream = new FileInputStream(zip);
  112. byte[] buf = new byte[4096];
  113. int readLength;
  114. while (((readLength = inStream.read(buf)) != -1)) {
  115. os.write(buf, 0, readLength);
  116. }
  117. } finally {
  118. if (inStream != null) {
  119. inStream.close();
  120. }
  121. if (os != null) {
  122. os.flush();
  123. os.close();
  124. }
  125. }
  126. }
  127. /**
  128. * 设置下载zip的响应头信息
  129. *
  130. * @param response 返回
  131. * @param fileName 文件名
  132. * @param request 请求
  133. * @throws IOException 异常
  134. */
  135. public static void setZipDownLoadHeadInfo(HttpServletResponse response, HttpServletRequest request, String fileName) throws IOException {
  136. // 获取客户端浏览器的类型
  137. String agent = request.getHeader("User-Agent");
  138. response.setContentType("application/octet-stream ");
  139. // 表示不能用浏览器直接打开
  140. response.setHeader("Connection", "close");
  141. // 告诉客户端允许断点续传多线程连接下载
  142. response.setHeader("Accept-Ranges", "bytes");
  143. // 对文件名重新编码
  144. String encodingFileName = FileDownloadUtils.encodeDownloadFilename(fileName, agent);
  145. response.setHeader("Content-Disposition", "attachment; filename=" + encodingFileName);
  146. }
  147. /**
  148. * 编译下载的文件名
  149. *
  150. * @param filename 文件名
  151. * @param agent 浏览器
  152. * @return String
  153. * @throws IOException 异常
  154. */
  155. public static String encodeDownloadFilename(String filename, String agent) throws IOException {
  156. if (agent.contains("Firefox")) {
  157. // 火狐浏览器
  158. filename = "=?UTF-8?B?"
  159. + new BASE64Encoder().encode(filename.getBytes("utf-8"))
  160. + "?=";
  161. filename = filename.replaceAll("\r\n", "");
  162. } else {
  163. // IE及其他浏览器
  164. filename = URLEncoder.encode(filename, "utf-8");
  165. filename = filename.replace("+", " ");
  166. }
  167. return filename;
  168. }
  169. /**
  170. * //压缩文件
  171. *
  172. * @param srcfile 要压缩的文件数组
  173. * @param zipfile 生成的zip文件对象
  174. */
  175. public static void ZipFiles(java.io.File[] srcfile, File zipfile) throws Exception {
  176. byte[] buf = new byte[1024];
  177. FileOutputStream fos = new FileOutputStream(zipfile);
  178. ZipOutputStream out = new ZipOutputStream(fos);
  179. for (File file : srcfile) {
  180. FileInputStream in = new FileInputStream(file);
  181. out.putNextEntry(new ZipEntry(file.getName()));
  182. int len;
  183. while ((len = in.read(buf)) > 0) {
  184. out.write(buf, 0, len);
  185. }
  186. out.closeEntry();
  187. in.close();
  188. }
  189. out.close();
  190. fos.flush();
  191. fos.close();
  192. }
  193. /**
  194. * 删除文件夹及文件夹下所有文件
  195. *
  196. * @param dir 文件地址
  197. * @return boolean
  198. */
  199. public static boolean deleteDir(File dir) {
  200. if (dir == null || !dir.exists()) {
  201. return true;
  202. }
  203. if (dir.isDirectory()) {
  204. String[] children = dir.list();
  205. //递归删除目录中的子目录下
  206. for (String child : children) {
  207. boolean success = deleteDir(new File(dir, child));
  208. if (!success) {
  209. return false;
  210. }
  211. }
  212. }
  213. // 目录此时为空,可以删除
  214. return dir.delete();
  215. }
  216. }

发表评论

表情:
评论列表 (有 0 条评论,107人围观)

还没有评论,来说两句吧...

相关阅读

    相关 File

    File File类封装了一个路径。 绝对路径是一个固定的路径,从盘符开始。 相对路径相对于某个位置,在eclipse是指当前项目下。 构造方法: Fi

    相关 Files

           创建文件        Files类中提供了createFile()方法,该方法用于实现创建文件。该方法语法格式如下:        Files.create

    相关 Files

    据说这个Files类在jdk1.7就有了 下面我们来了解一下常用的方法 创建文件 Files类中提供了createFile()方法,该方法用于实现创建文件。该方法语