文件处理类

package com.rbpm.service.Impl;

import ch.qos.logback.core.spi.ScanException;
import com.rbpm.service.FileService;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@Service
public class FileServiceImpl implements FileService {

    // 文件上传根目录
    @Value("${UPLOAD_URL}")
    private String UPLOAD_URL;

    // 下载的文件的根路径
    @Value("${download_URL}")
    private String download_URL;

    private Logger m_Logger = LoggerFactory.getLogger("FileServiceImpl");
    private Integer m_Index = 0;

    /**
     * @Description: 单文件上传
     * @Author:
     * @Date: 2018/4/9 17:15
     */
    public String upload(MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return "文件为空";
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            m_Logger.info("上传的文件名为:" + fileName);
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            m_Logger.info("文件的后缀名为:" + suffixName);

            // 设置文件存储路径
            String filePath = UPLOAD_URL;
            String path = filePath + fileName + suffixName;

            File dest = new File(path);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(dest);// 文件写入
            return "上传成功";
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

    /**
     * @Description: 创建文件夹
     * @Author:
     * @Date: 2018/4/9 17:15
     */
    public Map addFileFolder(HttpServletRequest request, String Path) {
        Map tResultMap = new HashMap();
        String mkDirectoryPath = Path;  // 路径格式:"d:\\aim\\y"

        File file = null;
        int j = 1;
        try {
            file = new File(Path);
            if (!file.exists()) {
                file.mkdirs();
            } else {
                while (file.exists()) {
                    mkDirectoryPath = Path + "-副本(" + getNum(j, Path) + ")";
                    file = new File(mkDirectoryPath);
                    file.mkdirs();
                    break;
                }
            }
            tResultMap.put("msg", "建立成功");
            System.out.println(mkDirectoryPath + "建立完毕");
        } catch (Exception e) {
            tResultMap.put("msg", "建立失败");
            System.out.println(mkDirectoryPath + "建立失败");
        } finally {
            file = null;
        }
        return tResultMap;
    }

    public int getNum(int i, String Path) {
        String path = Path + "-副本(" + i + ")";
        File file = new File(path);
        if (file.exists()) {
            i++;
            return getNum(i, Path);
        } else {
            return i;
        }
    }

    /**
     * @Description: 上传多个文件
     * @Author: Mr.Zhong
     * @Date: 2018/4/9 17:26
     */
    public String uploads(HttpServletRequest request, MultipartFile[] file) {
        try {
            //上传目录地址
            String uploadDir = request.getSession().getServletContext().getRealPath("/") + "upload/";
            //如果目录不存在,自动创建文件夹
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdir();
            }
            //遍历文件数组执行上传
            for (int i = 0; i < file.length; i++) {
                if (file[i] != null) {
                    //调用上传方法
                    executeUpload(uploadDir, file[i]);
                }
            }
        } catch (Exception e) {
            //打印错误堆栈信息
            e.printStackTrace();
            return "上传失败";
        }
        return "上传成功";
    }


    /**
     * 上传方法为公共方法
     */
    private void executeUpload(String uploadDir, MultipartFile file) throws Exception {
        //文件后缀名
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //上传文件名
        String filename = UUID.randomUUID() + suffix;
        //服务器端保存的文件对象
        File serverFile = new File(uploadDir + filename);
        //将上传的文件写入到服务器端文件内
        file.transferTo(serverFile);
    }

    /**
     * @Description: 扫描文件(根据父级目录查当前目录下的文件和文件夹)
     * @Author:
     * @Date: 2018/4/9 17:39
     */
    private static ArrayList<Object> scanFiles = new ArrayList<Object>();

    public Map scanFilesWithRecursion(String folderPath) throws ScanException {
        folderPath = UPLOAD_URL;
        folderPath.length();

        HashMap tResultMap = new HashMap();
        tResultMap.put("status", "failed");
        ArrayList<String> dirctorys = new ArrayList<String>();
        File directory = new File(folderPath);
        if (!directory.isDirectory()) {
            throw new ScanException('"' + folderPath + '"' + " input path is not a Directory , please input the right path of the Directory. ^_^...^_^");
        }

        File[] filelist = directory.listFiles();

        List tFolderList = new ArrayList();
        List tFilesList = new ArrayList();
        for (File tFile : filelist) {
            /**如果当前是文件夹,进入递归扫描文件夹**/
            if (tFile.isDirectory())
                tFolderList.add(tFile.getName());
            else {
                tFilesList.add(tFile.getName());
            }
        }
        tResultMap.put("folder", tFolderList);
        tResultMap.put("files", tFilesList);
        tResultMap.put("status", "success");
        return tResultMap;
    }

    /**
     * @Description: 获取目录树
     * @Author:
     * @Date: 2018/4/9 17:39
     */
    public Map scanFilesWithNoRecursion(String folderPath) {
        Map tResultMap = new HashMap();
        m_Index = 0;
        tResultMap.put("data", recursion(folderPath));
        return tResultMap;
    }

    /**
     * @Description: 获取目录树的处理方法
     * @Author:
     * @Date: 2018/4/9 17:39
     */
    public List recursion(String vFolderPath) {
        List tResultList = new ArrayList();

        File directory = new File(vFolderPath);
        File[] tfiles = directory.listFiles();

        for (File tFile : tfiles) {
            Map tMap = new HashMap();
            if (tFile.isDirectory()) {
                tMap.put("children", recursion(vFolderPath + "/" + tFile.getName()));
                tMap.put("label",tFile.getName());
                tMap.put("id", ++m_Index);
                tResultList.add(tMap);
            }

        }
        return tResultList;
    }

    /**
     * @Description: 下载
     * @Author:
     * @Date: 2018/4/9 17:39
     */
    public Map download(HttpServletResponse res) {
        Map tResultMap = new HashMap();
        String fileName = download_URL;
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File(UPLOAD_URL
                    + fileName)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("success");
        return tResultMap;
    }

    /**
     * @Description: 文件或文件夹重命名
     * @Author:
     * @Date: 2018/4/9 17:39
     */
    public Map updateFileName(String Path , String newPath) {

        Map tResultMap = new HashMap();

        //想命名的原文件的路径
        File file = new File(Path);
        if(file.exists()) {
            file.renameTo(new File(newPath));
            tResultMap.put("msg","修改文件名成功");
        }
        return tResultMap;
    }

    public Map deleteDirectory(List<String> pathList) {
        Map tResultMap = new HashMap();
        tResultMap.put("status","failed");

        for (int i=0;i<pathList.size();i++){
            deleteDirectoryDetail(UPLOAD_URL+pathList.get(i));
        }
        tResultMap.put("status","success");
        return tResultMap;
    }

    /**
     * 删除文件和文件夹
     * @param path
     * @return
     */
    public Map deleteDirectoryDetail(String path){
        Map tResultMap = new HashMap();
        //tResultMap.put("status","failed");
        // 如果dir不以文件分隔符结尾,自动添加文件分隔符
        if (!path.endsWith(File.separator))
            path = path + File.separator;
        File dir = new File(path);
        try {
            if(dir.exists()){
                File[] tmp=dir.listFiles();
                for(int i=0;i<tmp.length;i++){
                    if(tmp[i].isDirectory()){
                        deleteDirectoryDetail(path+"/"+tmp[i].getName());

                    }
                    else{
                        tmp[i].delete();
                        System.out.println(tmp[i]+"删除成功");
                    }
                }
                dir.delete();
                System.out.println(dir+"删除成功");
            }
            //tResultMap.put("status","success");
        }catch (Exception e){
            e.printStackTrace();
            tResultMap.put("msg",e.getMessage());
        }finally {
            return tResultMap;
        }


    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值