FileDownUtils.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package com.xunmei.file.utils;
  2. import com.xunmei.file.controller.SysFileController;
  3. import org.apache.commons.io.FileUtils;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import java.io.*;
  7. /**
  8. * 文件下载工具
  9. * @author gaoxiong
  10. */
  11. public class FileDownUtils {
  12. private static final Logger log = LoggerFactory.getLogger(FileDownUtils.class);
  13. /**
  14. * 下载文件
  15. * @param filePath 文件地址
  16. * @return
  17. */
  18. public static ByteArrayOutputStream downloadFile(String filePath) {
  19. File file = FileUtils.getFile(filePath);
  20. if (!file.exists()) {
  21. throw new RuntimeException("文件不存在!");
  22. }
  23. InputStream is = getInputStream(file);
  24. return convertInputStream(is);
  25. }
  26. /**
  27. * 获取文件输入流
  28. * @param file 文件对象
  29. * @return 文件输入流对象
  30. */
  31. public static InputStream getInputStream(File file) {
  32. FileInputStream fin;
  33. try {
  34. fin = new FileInputStream(file);
  35. } catch (FileNotFoundException e) {
  36. if (log.isDebugEnabled()) {
  37. log.debug(String.valueOf(e));
  38. }
  39. String msg = "找不到指定的文件[" + file.getName() + "]。";
  40. if (log.isDebugEnabled()) {
  41. log.debug(msg);
  42. }
  43. throw new RuntimeException(msg, e);
  44. }
  45. return fin;
  46. }
  47. /**
  48. * 输入流转换为输出流
  49. *
  50. * @param is 输入流
  51. * @return 输出流
  52. */
  53. public static ByteArrayOutputStream convertInputStream(InputStream is) {
  54. final byte[] by = new byte[1024];
  55. ByteArrayOutputStream data = new ByteArrayOutputStream();
  56. try {
  57. // 将内容读取内存中
  58. int len;
  59. while ((len = is.read(by)) != -1) {
  60. data.write(by, 0, len);
  61. }
  62. } catch (IOException e) {
  63. log.error("convertInputStream IO Exception", e);
  64. }
  65. return data;
  66. }
  67. /**
  68. * 文件后缀
  69. *
  70. * @param fileName 文件名或者文件路径
  71. * @return 后缀类型
  72. */
  73. public static String getFileSuffix(String fileName) {
  74. if (fileName == null) {
  75. return null;
  76. }
  77. return fileName.substring(fileName.lastIndexOf("."));
  78. }
  79. }