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();
        }
    }
相关推荐
这个人懒得名字都没写4 小时前
Python包管理新纪元:uv
python·conda·pip·uv
有泽改之_4 小时前
leetcode146、OrderedDict与lru_cache
python·leetcode·链表
无敌最俊朗@4 小时前
STL-vector面试剖析(面试复习4)
java·面试·职场和发展
是毛毛吧4 小时前
边打游戏边学Python的5个开源项目
python·开源·github·开源软件·pygame
PPPPickup4 小时前
easychat项目复盘---获取联系人列表,联系人详细,删除拉黑联系人
java·前端·javascript
LiamTuc4 小时前
Java构造函数
java·开发语言
三途河畔人5 小时前
Pytho基础语法_运算符
开发语言·python·入门
长安er5 小时前
LeetCode 206/92/25 链表翻转问题-“盒子-标签-纸条模型”
java·数据结构·算法·leetcode·链表·链表翻转
菜鸟plus+5 小时前
N+1查询
java·服务器·数据库
我要添砖java5 小时前
《JAVAEE》网络编程-什么是网络?
java·网络·java-ee