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();
        }
    }
相关推荐
皮皮林5516 小时前
IDEA 源码阅读利器,你居然还不会?
java·intellij idea
databook9 小时前
Manim实现闪光轨迹特效
后端·python·动效
Juchecar10 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
卡尔特斯10 小时前
Android Kotlin 项目代理配置【详细步骤(可选)】
android·java·kotlin
白鲸开源10 小时前
Ubuntu 22 下 DolphinScheduler 3.x 伪集群部署实录
java·ubuntu·开源
用户83562907805110 小时前
Python 删除 Excel 工作表中的空白行列
后端·python
Json_10 小时前
使用python-fastApi框架开发一个学校宿舍管理系统-前后端分离项目
后端·python·fastapi
ytadpole10 小时前
Java 25 新特性 更简洁、更高效、更现代
java·后端
纪莫11 小时前
A公司一面:类加载的过程是怎么样的? 双亲委派的优点和缺点? 产生fullGC的情况有哪些? spring的动态代理有哪些?区别是什么? 如何排查CPU使用率过高?
java·java面试⑧股
JavaGuide11 小时前
JDK 25(长期支持版) 发布,新特性解读!
java·后端