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();
        }
    }
相关推荐
源码之家几秒前
计算机毕业设计:Python二手车数据分析推荐系统 Flask框架 requests爬虫 协同过滤推荐算法 可视化 汽车之家 机器学习(建议收藏)✅
大数据·python·机器学习·数据分析·flask·汽车·课程设计
章鱼丸-10 分钟前
DAY43
python
禹中一只鱼16 分钟前
【力扣热题100学习笔记】 - 双指针
java·笔记·学习·leetcode·贪心算法
wangchunting16 分钟前
算法-二分查找
java·数据结构·算法
weixin_4563216418 分钟前
生产环境下微服务网关选型与实战指南(基于SpringCloud生态)
java·spring cloud
zero159720 分钟前
Python 8天极速入门笔记(大模型工程师专用):第七篇-文件操作 + 异常处理,大模型实战落地关键
python·ai编程·大模型编程语言
jwn99923 分钟前
PHP与C++:Web脚本与系统编程的终极对决
java·开发语言
Kk.080224 分钟前
数据结构|排序算法(三)堆排序
java·数据结构·排序算法
hnlgzb25 分钟前
Companion Object - 伴生对象 类比java中的什么?
java·开发语言
T0uken25 分钟前
【Python】uvpacker:跨平台打包 Windows 应用
开发语言·python