java FileUtils 文件操作

package pit.common.utils.file;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import pit.common.exception.ExceptionCast;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;


public class FileUtils {


    public static String saveFile(MultipartFile file, String roothttpPath) {

        String filename = file.getOriginalFilename();
        String extName = FileUtil.extName(filename);

        try {
            String fileMd5 = DigestUtils.md5Hex(file.getBytes());
            String filePath = roothttpPath + "/" + generateFilePath(fileMd5, extName);


            File targetFile = new File(filePath);
            if (targetFile.exists()) {
                return filePath;
            }

            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }
            file.transferTo(targetFile);

            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private static String generateFilePath(String fileMd5, String fileExt) {
        String one = fileMd5.substring(0, 1);
        String two = fileMd5.substring(1, 2);
        return one + "/" + two + "/" + fileMd5 + "/" +
                Base64.encode(String.valueOf(System.currentTimeMillis()).getBytes()) + "." + fileExt;
    }

    /**
     * @param request
     * @param response
     * @param absPath
     * @throws IOException
     */
    //文件下载
    public static void fileDownload(HttpServletRequest request, HttpServletResponse response, String absPath) throws IOException {
        //读取路径下面的文件
        File file = new File(absPath);
        if (file == null) {
            ExceptionCast.cast(-1, "文件不存在!");
        }

        String fileName = file.getName();

        //获取文件后缀名格式
        String ext = fileName.substring(fileName.indexOf("."));

        //判断图片格式,设置相应的输出文件格式
        if (ext.equals(".jpg")) {
            response.setContentType("image/jpeg");
        } else if (ext.equals(".JPG")) {
            response.setContentType("image/jpeg");
        } else if (ext.equals(".png")) {
            response.setContentType("image/png");
        } else if (ext.equals(".PNG")) {
            response.setContentType("image/png");
        } else {
            response.setContentType("application/octet-stream");
        }
        //将响应的类型设置为图片
        response.setHeader("Content-Disposition",
                "attachment;filename=" + RYFileUtils.setFileDownloadHeader(request, fileName));

        FileInputStream inputStream = new FileInputStream(file);

        //输出流
        OutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[2048];
        int length;
        while ((length = inputStream.read(bytes)) > 0) {
            outputStream.write(bytes, 0, length);
        }
        inputStream.close();
        outputStream.close();
        outputStream.flush();
    }

    public static void fileDownload(HttpServletRequest request, HttpServletResponse response, InputStream inputStream) throws IOException {
        //输出流
        OutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[2048];
        int length;
        while ((length = inputStream.read(bytes)) > 0) {
            outputStream.write(bytes, 0, length);
        }
        outputStream.flush();
        inputStream.close();
        outputStream.close();
    }

    public static boolean deleteFile(String pathname) {
        File file = new File(pathname);
        if (file.exists()) {
            boolean flag = file.delete();

            if (flag) {
                File[] files = file.getParentFile().listFiles();
                if (files == null || files.length == 0) {
                    file.getParentFile().delete();
                }
            }

            return flag;
        }

        return false;
    }

    public static String fileMd5(InputStream inputStream) {
        try {
            return DigestUtils.md5Hex(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String getPath() {
        return "/" + LocalDate.now().toString().replace("-", "/") + "/";
    }

    /**
     * 将文本写入文件
     *
     * @param value
     * @param path
     */
    public static void saveTextFile(String value, String path) {
        FileWriter writer = null;
        try {
            File file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            writer = new FileWriter(file);
            writer.write(value);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,您想了解在 Spring Boot 中如何实现文件上传和下载功能,对吧?那么,我给您简单介绍一下。 首先,在 Spring Boot 中实现文件上传和下载功能,需要用到 Commons FileUpload 和 Commons IO 这两个工具包。您可以在 Maven 中添加以下依赖: ```xml <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.8.0</version> </dependency> ``` 接下来,我们来看一下文件上传的实现。在 Spring Boot 中,我们可以使用 MultipartFile 类来接收上传的文件。在处理上传请求时,我们需要先判断请求是否为文件上传请求,如果是,则使用 MultipartFile 类来接收上传的文件,并将文件保存到指定的目录中。 ```java @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file) throws IOException { if (!file.isEmpty()) { // 获取文件名 String fileName = file.getOriginalFilename(); // 构建文件保存的路径 String filePath = "D:/upload/"; // 创建文件对象 File dest = new File(filePath + fileName); // 判断目标文件所在的目录是否存在,如果不存在则创建目录 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } // 保存文件 file.transferTo(dest); return "上传成功!"; } return "上传失败!"; } ``` 接下来,我们来看一下文件下载的实现。在 Spring Boot 中,我们可以使用 ResponseEntity 类来将文件以流的形式返回给前端。 ```java @GetMapping("/download") public ResponseEntity<byte[]> download() throws IOException { // 构建文件对象 File file = new File("D:/upload/test.txt"); // 文件不存在 if (!file.exists()) { return ResponseEntity.notFound().build(); } // 构建文件下载的响应头 HttpHeaders headers = new HttpHeaders(); headers.setContentDispositionFormData("attachment", file.getName()); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); // 使用 FileUtils 工具类将文件转换成字节数组 byte[] bytes = FileUtils.readFileToByteArray(file); // 返回响应实体对象 return new ResponseEntity<>(bytes, headers, HttpStatus.OK); } ``` 以上就是 Spring Boot 中实现文件上传和下载的基本步骤。需要注意的是,这只是一个简单的示例,实际应用中还需要进行参数校验、异常处理等其他操作

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值