Java文件工具类


package com.yunphant.iie.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @description: 工具类
 */

@Slf4j
public class FileUtils {




    public static MultipartFile FileToMultipart(File file){
        FileInputStream fileInputStream = null;
        MultipartFile multipartFile = null;
        try {
            fileInputStream = new FileInputStream(file);
            multipartFile = new MockMultipartFile(file.getName(),file.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(),fileInputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return multipartFile;
    }


    public static File MultipartFileToFile(MultipartFile multipartFile) {
        //文件上传前的名称
        String fileName = multipartFile.getOriginalFilename();
        File file = new File(fileName);
        OutputStream out = null;
        try{
            //获取文件流,以文件流的方式输出到新文件
//    InputStream in = multipartFile.getInputStream();
            out = new FileOutputStream(file);
            byte[] ss = multipartFile.getBytes();
            for(int i = 0; i < ss.length; i++){
                out.write(ss[i]);
            }
        }catch(IOException e){
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //业务完成后,代码补充删除文件代码
//        if (f.delete()){
//            System.out.println("删除成功");
//        }else {
//            System.out.println("删除失败");
//        }

        return file;




    }

    /**
     * 创建文件夹
     * @param filePath
     * @return
     */
    public static String creatyFolder(String filePath) {
        File pfile = new File(filePath);
        //判断文件夹是否存在
        if(!pfile.exists()){
            //不存在时,创建文件夹
            pfile.mkdirs();
        }
        return filePath;
    }



    /**
     * 写入文件
     * @param files 文件字符串
     * @return
     */
    public static String writeFile(String files,String filePath,String fileName) {
        StringBuilder result = new StringBuilder();
        try {
            File writename = new File(filePath+"/"+fileName); // 相对路径
            writename.createNewFile(); // 创建新文件
            BufferedWriter out = new BufferedWriter(new FileWriter(writename));
            out.write(files);
            out.flush();
            out.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(result);
    }


    /**
     * 根据文件路径读取文件内容
     * @param filePath
     * @return
     */
    public static String readFile(String filePath) {
        StringBuilder result = new StringBuilder();
        try {
//          BufferedReader bfr = new BufferedReader(new FileReader(new File(filePath)));
            BufferedReader bfr = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath)), "UTF-8"));
            String lineTxt = null;
            while ((lineTxt = bfr.readLine()) != null) {
                result.append(lineTxt).append("\n");
            }
            bfr.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(result);
    }


    /**
     * 文件删除 ( new File(filePath) )
     * @param filePath
     * @return
     * @throws Exception
     */
    public static boolean  deleteFolder(File filePath) throws Exception {
        boolean flag = false;
        if (!filePath.exists()) {
            throw new Exception("文件不存在");
        }
        File[] files = filePath.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    //递归直到目录下没有文件
                    deleteFolder(file);
                    System.err.println("删除目录下所有文件");
                    flag=true;
                } else {
                    //删除
                    file.delete();
                    System.err.println("删除文件夹里面的文件");
                    flag=true;
                }
            }
        }
        //删除
        filePath.delete();
        System.err.println("删除文件夹");
        return flag;
    }


    /**
     * 文件上传
     * @param files 文件
     * @param filePath 保存路径
     * @return
     */
    public static String upLoadFile(MultipartFile files, String filePath) {
        String fileName = files.getOriginalFilename();
        try {
            //获取文件字节数组
            byte [] bytes = files.getBytes();
            //文件存储路径(/fileupload1/ 这样会在根目录下创建问价夹)
            File pfile = new File(filePath);
            //判断文件夹是否存在
            if(!pfile.exists()){
                //不存在时,创建文件夹
                pfile.mkdirs();
            }
            //创建文件
            File file = new File(pfile, fileName);
            //写入指定文件夹
            OutputStream out = new FileOutputStream(file);
            out.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败";
        }
        String path = filePath + "/" + fileName;
        log.info("上传文件保存路径:" + path);
        return path;

    }


    /**
     * 文件下载
     * @param response
     * @param path     保存路径
     */
    public HttpServletResponse downloadFile(HttpServletResponse response, String path) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;

    }



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值