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();
        }
    }
相关推荐
mldong2 小时前
一个 App,十三套后端:手机审批端 uni-jeeflow-app 开源了
java·架构
qq5918406853 小时前
uiautomator2自动化安卓手机操作
python
tqs_123453 小时前
MySQL RR隔离级别死锁|Gap间隙锁、临键锁,订单并发范围查询死锁根因方案
java
80s7773 小时前
动态代理和静态代理的区别,动态代理怎么提高网络安全性
python
逆境不可逃3 小时前
Pi Agent 学习笔记:多个工具怎样并行执行
java
Flynt4 小时前
Java 27 升级实测:默认值动得比新特性多,有个老参数会让 JVM 直接起不来
java·jvm·后端
Bs_MoneyMagnet4 小时前
基于springboot+vue的个人健康管理系统的设计与实现 源码+文档
java·vue.js·spring boot·后端·vue3·springboot3·计算机毕业设计
星云API技术支持5 小时前
企业微信二次开发:群权限设置、成员管理与群资料维护的接口组合实践
java·前端·企业微信
niucloud-admin5 小时前
JAVA V6 多商户商城 开发文档——job 计划任务开发
java·python·github
小叶肥辉5 小时前
LangChain链和LangGraph图的学习笔记【三】——分别用langchain_openai库和langchain_community库调用大模型
笔记·python·langchain