java 下载文件,复制文件

1,java通过浏览器下载文件

bash 复制代码
    @ApiOperation(value = "导出", notes = "", response = String.class)
    @GetMapping("/export")
    public HttpServletResponse export(String path, HttpServletResponse response) {
//        String path = "/home/lilun.txt";

        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;
    }

2,复制文件到其他文件夹

bash 复制代码
    //复制文件到指定文件夹
    public void copyFile(String path){
        int lastIndex = path.lastIndexOf("/");
        String fileName = path.substring(lastIndex+1,path.length());
        String targetDir = "/home/fy/targetexportdata/";
        String targetDirFile = targetDir+fileName;
        File fs = new File(targetDir);
        if (!fs.exists()) {
            fs.mkdirs();
        }
        try (FileInputStream fis = new FileInputStream(path);
             FileOutputStream fos = new FileOutputStream(targetDirFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            System.out.println("文件复制成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
相关推荐
用户398346161209 分钟前
Go-Spring 实战第 15 课 —— Condition:根据配置和上下文激活 Bean
spring·go
l1t11 分钟前
DeepSeek总结的使用实体-组件-系统和基于存在性处理进行Python编程18-20
开发语言·python
零梦ing18 分钟前
Claude Code 升级后 DeepSeek API 报错 messages[x].role: unknown variant system 终极解决方案
python·claude code·deepseek api 代理
凤山老林19 分钟前
DDD(领域驱动设计)在复杂业务系统中的落地指南
java·开发语言·数据库·ddd·领域驱动
JEECG低代码平台24 分钟前
JimuChatBI — 首款免费开源的 Java 智能问数ChatBI平台,零成本接入,AI对话式智能分析
java·人工智能·开源·aigc·人工智能低代码
Eiceblue31 分钟前
Python 操作 Excel:数据分组、分类汇总与取消分组全解
开发语言·python·excel
霸道流氓气质32 分钟前
SpringBoot中使用Spring AI框架集成本地Ollama实现AI快速对话完整示例
人工智能·spring boot·spring
暴躁小师兄数据学院1 小时前
【AI大模型应用开发工程师特训笔记】第04讲(第9章):文件目录操作
人工智能·笔记·python
星梦清河1 小时前
Java—异步编程
java·开发语言
GIS数据转换器1 小时前
智慧能源管理平台
java·大数据·运维·人工智能·无人机