Springboot文件操作

该文详细介绍了如何使用Springboot进行文件操作,包括将字符串写入流以生成可下载的文件,读取本地文件内容,上传文件到服务器,以及文件的压缩和下载功能实现。代码示例涵盖了HTTP响应设置、文件流处理和Zip压缩算法的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Springboot文件操作

1、将字符串写入流,前端生成文件并下载

@RequestMapping(value = "/download")
public void downloadParam(HttpServletResponse response) {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html");
    response.setHeader("Content-Disposition", "attachment;fileName=a.txt");
    String content = "Hello, Txt World!";
    try {
        OutputStream os = response.getOutputStream();
        os.write(content.getBytes(StandardCharsets.UTF_8));
        os.close();
    } catch (IOException e) {
        LOGGER.error("文件下载失败", e);
    }
}

2、读取本地文件内容

 /**
     * 读取本地文件内容
     * @param fileName 文件路径 /data/code/jni/test.cer
     * @return
     */
public  String readFile(String fileName){
    System.out.println(fileName);
    File file = new File(fileName);
    Scanner sc = null;
    try {
        sc = new Scanner(file);
        sc.useDelimiter("\\Z");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return sc.next();
}

3、上传文件

/**
 * 本地上传文件
 *
 * @return
 */
@Operation(summary = "本地上传文件")
@PostMapping("/uploadFile")
public Object uploadFile(@RequestParam("file") MultipartFile file) {
        //判断文件是否存在
        File tempFile = new File(file.getOriginalFilename());
        boolean exists = tempFile.exists();
        if (exists) {
            //存在即删除
            deleteTempFile(tempFile);
        }
        //上传文件
        File result = multipartFileToFile(file);
        String absolutePath = result.getAbsolutePath();
}

/**
 * MultipartFile 转 File
 *
 * @param file
 * @throws Exception
*/
public static File multipartFileToFile(MultipartFile file) {
    try {
        File toFile;
        if (file != null && file.getSize() > 0) {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
            return toFile;
        }
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

/**
 * 获取流文件
 *
 * @param ins
 * @param file
*/
public static void inputStreamToFile(InputStream ins, File file) {
    try {
        OutputStream os = new FileOutputStream(file);
        int bytesRead;
        byte[] buffer = new byte[8192];
        while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * 删除本地临时文件
 *
 * @param file
*/
public static void deleteTempFile(File file) {
    if (file != null) {
        File del = new File(file.toURI());
        del.delete();
    }
}

4、文件压缩和下载

文件打包工具类

package com.genersoft.iot.vmp.info.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 文件打包工具类
 */
public class ZipUtils {

    /**
     * 压缩前的文件校验和压缩后压缩文件的构件
     *
     * @param path   要压缩的文件路径
     * @param format 生成的格式(zip、rar)d
     */
    public static void generateFile(String path, String format) throws Exception {

        File file = new File(path);
        // 压缩文件的路径不存在
        if (!file.exists()) {
            throw new Exception("路径 " + path + " 不存在文件,无法进行压缩...");
        }
        // 用于存放压缩文件的文件夹
        File compress = new File(file.getParent());
        // 如果文件夹不存在,进行创建
        if (!compress.exists()) {
            compress.mkdirs();
        }

        // 目的压缩文件
        String absolutePath = compress.getAbsolutePath();
        // 定义压缩操作后,压缩文件的名称,本次采取  文件名XXX.XXX 的形式进行定义(可以自定义)
        String generateFileName = absolutePath + File.separator + file.getName()  + "." + format ;

        // 压缩文件数据的输出流:用于将压缩文件的数据存储至指定的压缩文件中
        FileOutputStream outputStream = new FileOutputStream(generateFileName);

        // 压缩输出流
        ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(outputStream));

        zipFile(zipOutputStream, file, "");

        System.out.println("源文件位置:" + file.getAbsolutePath() + ",目的压缩文件生成位置:" + generateFileName);
        // 关闭 输出流
        zipOutputStream.close();
    }

    /**
     * 主要的打包压缩操作
     *
     * @param out  输出流
     * @param file 目标文件
     * @param dir  文件夹
     * @throws Exception
     */
    private static void zipFile(ZipOutputStream out, File file, String dir) throws Exception {

        // 如果是文件夹,则采取递归方式继续检索,获取到最终的文件为止,当然这里有性能问题,文件足够大会性能降低
        if (file.isDirectory()) {
            //得到文件列表信息
            File[] files = file.listFiles();

            // 将文件夹添加到下一级打包目录
            // 这里的打包目录必须是每个新的目录(或文件)都需要额外创建新的 ZipEntry 对象
            out.putNextEntry(new ZipEntry(dir + File.separator));

            dir = dir.length() == 0 ? "" : dir + File.separator;

            // 文件夹,则采取递归继续检索,直到识别是文件为止
            for (int i = 0; i < files.length; i++) {
                zipFile(out, files[i], dir + files[i].getName());
            }

            return;
        }

        // 当识别到的 File 对象 是文件时,执行下列逻辑
        // 将文件信息,以流的形式读取到内存中
        FileInputStream inputStream = new FileInputStream(file);
        // 每个新的文件,都需要额外创建一个新的  ZipEntry
        // 将需要打包的文件,放置于新的条目中
        out.putNextEntry(new ZipEntry(dir));

        // 将文件流中的数据信息,分段读取并写入至对应的输出流中
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = inputStream.read(bytes)) > 0) {
            out.write(bytes, 0, len);
        }
        // 关闭单个流程资源
        out.closeEntry();

        // 关闭输入流
        inputStream.close();
    }
}

调用示例

    public void backFile(){
        String path = "F:\\home";
        String format = "zip";
        try {
            ZipUtils.generateFile(path, format);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

下载zip文件

     /**
     * 设置导出zip的响应格式
     *
     * @param request
     * @param response
     * @throws UnsupportedEncodingException
     */
    public static void downFile(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

        String fileZip = "home.zip";
        String filePath = "F:\\home.zip";
        // 如果是文件夹,则抛出异常
        File file = new File(filePath);
        if(file.isDirectory()){
            throw new RuntimeException("这是文件夹,暂不支持下载!");
        }

        // 判断文件是否存在
        if(!file.exists()){
            throw new RuntimeException("文件不存在!");
        }

        //进行浏览器下载
        final String userAgent = request.getHeader("USER-AGENT");
        //判断浏览器代理并分别设置响应给浏览器的编码格式
        String finalFileName = null;
        if (StringUtils.contains(userAgent, "MSIE") || StringUtils.contains(userAgent, "Trident")) {
            // IE浏览器
            finalFileName = URLEncoder.encode(fileZip, "UTF8");
            System.out.println("IE浏览器");
        } else if (StringUtils.contains(userAgent, "Mozilla")) {
            // google,火狐浏览器
            finalFileName = new String(fileZip.getBytes(), "ISO8859-1");
        } else {
            // 其他浏览器
            finalFileName = URLEncoder.encode(fileZip, "UTF8");
        }
        // 告知浏览器下载文件,而不是直接打开,浏览器默认为打开
        response.setContentType("application/x-download");

        // 解决下载文件名乱码的问题
        String disposition  = "attachment;filename=" + URLEncoder.encode(finalFileName, "utf-8");
        response.setHeader("Content-Disposition", disposition);


        ServletOutputStream servletOutputStream = null;
        try {
            servletOutputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        DataOutputStream temps = new DataOutputStream(
                servletOutputStream);
        // 浏览器下载文件的路径
        DataInputStream in = null;
        try {
            in = new DataInputStream(
                    new FileInputStream(filePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        byte[] b = new byte[2048];
        // 之后用来删除临时压缩文件
        File reportZip = new File(filePath);
        try {
            while ((in.read(b)) != -1) {
                temps.write(b);
            }
            temps.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (temps != null) {
                try {
                    temps.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reportZip != null) {
                // 删除服务器本地产生的临时压缩文件!
                reportZip.delete();
            }
            try {
                servletOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值