| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- package com.xunmei.file.utils;
- import com.xunmei.file.controller.SysFileController;
- import org.apache.commons.io.FileUtils;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import java.io.*;
- /**
- * 文件下载工具
- * @author gaoxiong
- */
- public class FileDownUtils {
- private static final Logger log = LoggerFactory.getLogger(FileDownUtils.class);
- /**
- * 下载文件
- * @param filePath 文件地址
- * @return
- */
- public static ByteArrayOutputStream downloadFile(String filePath) {
- File file = FileUtils.getFile(filePath);
- if (!file.exists()) {
- throw new RuntimeException("文件不存在!");
- }
- InputStream is = getInputStream(file);
- return convertInputStream(is);
- }
- /**
- * 获取文件输入流
- * @param file 文件对象
- * @return 文件输入流对象
- */
- public static InputStream getInputStream(File file) {
- FileInputStream fin;
- try {
- fin = new FileInputStream(file);
- } catch (FileNotFoundException e) {
- if (log.isDebugEnabled()) {
- log.debug(String.valueOf(e));
- }
- String msg = "找不到指定的文件[" + file.getName() + "]。";
- if (log.isDebugEnabled()) {
- log.debug(msg);
- }
- throw new RuntimeException(msg, e);
- }
- return fin;
- }
- /**
- * 输入流转换为输出流
- *
- * @param is 输入流
- * @return 输出流
- */
- public static ByteArrayOutputStream convertInputStream(InputStream is) {
- final byte[] by = new byte[1024];
- ByteArrayOutputStream data = new ByteArrayOutputStream();
- try {
- // 将内容读取内存中
- int len;
- while ((len = is.read(by)) != -1) {
- data.write(by, 0, len);
- }
- } catch (IOException e) {
- log.error("convertInputStream IO Exception", e);
- }
- return data;
- }
- /**
- * 文件后缀
- *
- * @param fileName 文件名或者文件路径
- * @return 后缀类型
- */
- public static String getFileSuffix(String fileName) {
- if (fileName == null) {
- return null;
- }
- return fileName.substring(fileName.lastIndexOf("."));
- }
- }
|