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();
        }
    }
相关推荐
MarkHD1 分钟前
智能体在车联网中的应用:第12天 Python科学计算双雄:掌握NumPy与Pandas,筑牢AI与自动驾驶数据基石
人工智能·python·numpy
TH_11 分钟前
18、删除WPSOfficeWord文档中的空白页
java
一雨方知深秋3 分钟前
数组定义及访问
java·数组·二维数组·for·length·定义访问
alanesnape5 分钟前
Java异常处理详解:Exception、ArithmeticException、FileNotFoundException
java·开发语言
while(1){yan}5 分钟前
数据链路层与物理层
java·网络·网络协议
野蛮人6号6 分钟前
黑马微服务 p23Docker02 docker的安装 如何正确安装docker,黑马微服务给的文档不行了,如何正确找到解决方法
java·docker·微服务·架构
hhhh明6 分钟前
日志重定向
python
再__努力1点8 分钟前
【78】HOG+SVM行人检测实践指南:从算法原理到python实现
开发语言·人工智能·python·算法·机器学习·支持向量机·计算机视觉
武子康20 分钟前
Java-206 RabbitMQ 发布订阅(fanout)Java 实战:推/拉模式、ACK 与绑定排错全梳理
java·分布式·消息队列·rabbitmq·rocketmq·java-rabbitmq·mq