Java下载文件的几种方式「建议收藏」

Java下载文件的几种方式「建议收藏」1.以流的方式下载.publicHttpServletResponsedownload(Stringpath,HttpServletResponseresponse){try{//path是指欲下载的文件的路径。Filefile=newFile(path);//取得文件名…

大家好,又见面了,我是你们的朋友全栈君。

1.以流的方式下载.

public HttpServletResponse download(String path, HttpServletResponse response) {
        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.下载本地文件

public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {
        // 下载本地文件
        String fileName = "Operator.doc".toString(); // 文件的默认保存名
        // 读到流中
        InputStream inStream = new FileInputStream("c:/Operator.doc");// 文件的存放路径
        // 设置输出的格式
        response.reset();
        response.setContentType("bin");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

3.下载网络文件

public void downloadNet(HttpServletResponse response) throws MalformedURLException {
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;

        URL url = new URL("windine.blogdriver.com/logo.gif");

        try {
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream("c:/abc.gif");

            byte[] buffer = new byte[1204];
            int length;
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                System.out.println(bytesum);
                fs.write(buffer, 0, byteread);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

4.支持在线打开的方式

public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {
        File f = new File(filePath);
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;

        response.reset(); // 非常重要
        if (isOnLine) { // 在线打开方式
            URL u = new URL("file:///" + filePath);
            response.setContentType(u.openConnection().getContentType());
            response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
            // 文件名应该编码成UTF-8
        } else { // 纯下载方式
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
        }
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0)
            out.write(buf, 0, len);
        br.close();
        out.close();
    }

 

喜欢本文的朋友们,欢迎关注微信公众号“Java面试达人”,收看更多精彩内容

Java下载文件的几种方式「建议收藏」

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/156262.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • File i/o3

    File i/o3

    2022年3月3日
    38
  • python找出肇事者_犯交通肇事罪的量刑级

    python找出肇事者_犯交通肇事罪的量刑级抓交通肇事犯1.问题描述一辆卡车违反交通规则,撞人后逃跑。现场有三人目击该事件,但都没有记住车号,只记下了车号的一些特征。甲说:牌照的前两位数字是相同的:乙说:牌照的后两位数字是相同的,但与前两位

    2022年7月30日
    22
  • JavaScript交互式网页设计 • 【第3章 JavaScript浏览器对象模型】

    JavaScript交互式网页设计 • 【第3章 JavaScript浏览器对象模型】全部章节>>>>本章目录3.1浏览器对象模型3.1.1浏览器对象模型3.2window对象3.2.1window对象的常用属性及方法3.2.2使用window对象创建对话框3.2.3使用window对象操作窗口3.2.4使用window对象执行计时事件3.2.5实践练习3.3history对象和location对象3.3.1history对象3.3.2location对象3.3.3实践练习..

    2022年10月20日
    3
  • setbackground参数_setcookie参数

    setbackground参数_setcookie参数setrequestproperty设置http请求头HttpURLConnection.setRequestProperty(Stringkey,Stringvalue);这个我居然都忘记了,哎~真是岁数大了,心好累。。。例如:下面就是一个完整的原始网络请求方式HttpURLConnectionconn=null;try{URLmy_url=newURL(log());//得…

    2025年10月22日
    6
  • j-link接口定义及实际使用[通俗易懂]

    j-link接口定义及实际使用[通俗易懂]使用j-link下载程序或者在线调试的时候,有两种模式:JTAG和SWD可以在keil中选择:下面是两种模式下,分别用的接口引脚:推荐使用SWD模式,因为更省引脚而且调试功能不受影响。在SWD模式下,实际只需要4个IO口就可以了,包括下载程序和在线调试。分别为:PA13/JTMS/SWDIO、PA14/JTCK/SWCLK、VCC、GND

    2022年5月28日
    107
  • 在pycharm中更新pip失败

    在pycharm中更新pip失败尝试了网上的各种方法 各种翻车删除虚拟环境中的这两个文件夹 包括 pip 有只删除 pip 21 1 2 dist info 这个个文件夹然后重新安装 pip 之后在更新 我试了没有用下载 get pip py 文件 转到 https bootstrap pypa io get pip py 后直接右键另存为到这个文件夹下 上面删除步骤打开的文件夹 在 pycharm 的终端 进入到虚拟环境文件夹下 输入 python mensurepipde pip 这时候在设置里能看到安装了更新的

    2025年10月10日
    3

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号