Java实现下载文件的6种方式

 更新时间:2023年06月09日 09:09:23   作者:佳德_Boy  
本文主要介绍了Java实现下载文件的6种方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

一、以流的方式下载

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;
    }

二、下载本地文件

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();
        }
    }

三、下载网络文件

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();
        }
    }
public void downLoadFile(HttpServletResponse response, String httpUrl) {
        ServletOutputStream out = null;
        try {
            //与服务器建立连接
            URL url = new URL(httpUrl);
            URLConnection conn = url.openConnection();
            InputStream inputStream = conn.getInputStream();
            try {
                //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
                response.setContentType("multipart/form-data");
            } catch (Exception e){
                e.printStackTrace();
            }
            out = response.getOutputStream();
            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            out.close();
            inputStream.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }

四、在线打开的方式

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();
    }

五、将文件转换成base64

    /**
     * 将文件转为base64
     */
    public static String getBase64FromFile(File file) throws IOException {
        FileInputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = new FileInputStream(file);
            out = new ByteArrayOutputStream();
            int read = 0;
            byte[] buffer = new byte[1024];
            while ((read = in.read(buffer, 0, 1024)) != -1) {
                out.write(buffer, 0, read);
            }
            return Base64.getEncoder().encodeToString(out.toByteArray());
        } catch (IOException e) {
            throw e;
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null){
                out.close();
            }
        }
    }

六、将MultipartFile转换为File

    /**
     * 将MultipartFile转换为File
     */
    public static File MultipartFileToFile(MultipartFile multiFile) throws IOException {
        String fileName = multiFile.getOriginalFilename();
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        InputStream in = null;
        OutputStream out = null;
        try {
            File file = File.createTempFile(fileName, prefix);
            out = new FileOutputStream(file);
            in = multiFile.getInputStream();
            int read = 0;
            byte[] buffer = new byte[1024];
            while ((read = in.read(buffer, 0, 1024)) != -1) {
                out.write(buffer, 0, read);
            }
            return file;
        } catch (Exception e) {
            throw e;
        }finally {
            if (in != null){
                in.close();
            }
            if (out != null){
                out.close();
            }
        }
    }

到此这篇关于Java实现下载文件的6种方式的文章就介绍到这了,更多相关Java 下载文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java-文件File简单实用方法(分享)

    Java-文件File简单实用方法(分享)

    下面小编就为大家带来一篇Java-文件File简单实用方法(分享)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-08-08
  • JAVA面向对象之继承 super入门解析

    JAVA面向对象之继承 super入门解析

    在JAVA类中使用super来引用父类的成分,用this来引用当前对象,如果一个类从另外一个类继承,我们new这个子类的实例对象的时候,这个子类对象里面会有一个父类对象。怎么引用里面的父类对象呢?用super来引用,this指当前对象的引用,super是当前对象里面的父对象的引用
    2022-01-01
  • IDEA使用MyBatisCodeHelperPro来generator代码的详细教程

    IDEA使用MyBatisCodeHelperPro来generator代码的详细教程

    这篇文章主要介绍了IDEA使用MyBatisCodeHelperPro来generator代码的详细教程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-09-09
  • SpringBoot thymeleaf eclipse热部署方案操作步骤

    SpringBoot thymeleaf eclipse热部署方案操作步骤

    今天小编就为大家分享一篇关于SpringBoot thymeleaf eclipse热部署方案操作步骤,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-03-03
  • java定义数组的三种类型总结

    java定义数组的三种类型总结

    下面小编就为大家带来一篇java定义数组的三种类型总结。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-10-10
  • Java实现的串口通信功能示例

    Java实现的串口通信功能示例

    这篇文章主要介绍了Java实现的串口通信功能,结合实例形式分析了java串口通信的具体操作步骤与相关注意事项,需要的朋友可以参考下
    2018-01-01
  • Shiro:自定义Realm实现权限管理方式

    Shiro:自定义Realm实现权限管理方式

    这篇文章主要介绍了Shiro:自定义Realm实现权限管理方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-10-10
  • java调用js文件的两种常用方法示例(支持V8引擎)

    java调用js文件的两种常用方法示例(支持V8引擎)

    在Java中调用JavaScript的方法通常涉及到使用Java的脚本引擎,下面这篇文章主要给大家介绍了关于java调用js文件的两种常用方法(支持V8引擎)的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2024-06-06
  • 运行Jar包出现提示xxx中没有主清单属性报错问题解决方法

    运行Jar包出现提示xxx中没有主清单属性报错问题解决方法

    这篇文章主要介绍了运行Jar包出现:xxx中没有主清单属性报错,当出现报错:xxx中没有主清单属性,解决方法也很简单,在pom.xml配置中,加上相应配置即可,需要的朋友可以参考下
    2023-08-08
  • Jaxb2实现JavaBean与xml互转的方法详解

    Jaxb2实现JavaBean与xml互转的方法详解

    这篇文章主要介绍了Jaxb2实现JavaBean与xml互转的方法,简单介绍了JAXB的概念、功能及实现JavaBean与xml互转的具体操作技巧,需要的朋友可以参考下
    2017-04-04

最新评论