Java根据url下载文件到本地

为了直观展示,方法中指定了文件后缀为.jpg,只下载图片

如果下载其他格式文件的话指定其他后缀,或把要输出的文件名也改成参数

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

//---------------------------------------------------------

public static String download(String urlString) {
        InputStream is = null;
        FileOutputStream os = null;
        try {
            // 构造URL
            URL url = new URL(urlString);
            // 打开连接
            URLConnection con = url.openConnection();
            // 输入流
            is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            String filename = System.getProperty("os.name").toLowerCase().contains("win") ? System.getProperty("user.home") + "\\Desktop\\temp.jpg" : "/home/project/temp.jpg";
            File file = new File(filename);
            os = new FileOutputStream(file, true);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }

            return filename;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 完毕,关闭所有链接
            try {
                if (null != os) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (null != is) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //从微信下载图片时如果没有id对应的图片则下载一个空图片,不会存在返回为null的情况
        return null;
    }

有下载肯定要有删除,也以删除图片为例,可根据需要自行调整

    public static Boolean deleteImage() {
        File file = new File(System.getProperty("os.name").toLowerCase().contains("win") ? System.getProperty("user.home") + "\\Desktop\\temp.jpg" : "/home/project/temp.jpg");
        return !file.exists() || file.delete();
    }

//------------------业务中我是这样用的删除----------------------------

    private Boolean deleteImage() {
        int i = 0;
        boolean flag = deleteImage();
        while (i >= 3 || !flag) {
            i++;
            flag = deleteImage();
        }
        return flag;
    }

  • 6
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用SpringBoot来实现根据URL下载文件到本地的功能。以下是一个示例代码: ```java @GetMapping("/download") public void download(@RequestParam("url") String urlStr, HttpServletResponse response) throws IOException { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); try (InputStream inputStream = conn.getInputStream(); OutputStream outputStream = new FileOutputStream("路径/文件名")) { byte[] buffer = new byte<span class="em">1</span><span class="em">2</span> #### 引用[.reference_title] - *1* [SpringBoot实现通过url下载pdf到本地](https://blog.csdn.net/MCmango/article/details/113937695)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [Vue+SpringBoot根据url返回文件流给前端下载文件(多个图片zip下载)](https://blog.csdn.net/zcl520sy/article/details/130142189)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值