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();
        }
    }
相关推荐
亿.66 分钟前
【Java安全】RMI基础
java·安全·ctf·rmi
ruan11451421 分钟前
Java Lambda 类型推断详解:filter() 方法与 Predicate<? super T>
java·开发语言·spring·stream
猿榜22 分钟前
魔改编译-永久解决selenium痕迹(二)
javascript·python
朱杰jjj23 分钟前
解决jenkins的Exec command命令nohup java -jar不启动问题
java·jenkins·jar
广东数字化转型24 分钟前
java jar 启动应用程序
开发语言·python
上上迁36 分钟前
分布式接口幂等性的演进和最佳实践,含springBoot 实现(Java版本)
java·spring boot·分布式
匚WYHaovous36 分钟前
Java断言的深度解析与实战指南
java
WanderInk1 小时前
揭秘Java协变返回类型:让你的API少一点强转,多一点优雅
java·后端
费弗里1 小时前
Python全栈应用开发利器Dash 3.x新版本介绍(4)
python·dash
paopaokaka_luck1 小时前
基于SpringBoot+Vue的非遗文化传承管理系统(websocket即时通讯、协同过滤算法、支付宝沙盒支付、可分享链接、功能量非常大)
java·数据库·vue.js·spring boot·后端·spring·小程序