Java实现下载文件功能到本地电脑中,附源码和截图

x33g5p2x  于2022-08-17 转载在 Java  
字(1.6k)|赞(0)|评价(0)|浏览(489)

实现下载文件功能到本地电脑的完整源码

package com.example.springbootdownloadfile.file;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class DownFileBaiduPic {
    private static Logger logger = LoggerFactory.getLogger(DownFileBaiduPic.class);
    public static void main(String[] args) {
        String filerootpath="E:\\resource";
        String url="https://t7.baidu.com/it/u=3569419905,626536365&fm=193&f=GIF";
        String fileName="demo.png";
        download(url,filerootpath+"\\"+fileName);
    }

    /**
     * 文件下载
     *
     * @param fileUrl
     *      文件url,如:<code></code>
     * @param fileName
     *      存放路径,如: /opt/img/douban/my.webp
     */
    public static void download(String fileUrl, String fileName) {
        // 判断存储文件夹是否已经存在或者创建成功
        if(!createFolderIfNotExists(fileName)) {
            return;
        }

        InputStream in = null;
        FileOutputStream out = null;
        try {
            URL url = new URL(fileUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // 2s
            conn.setConnectTimeout(10000);
            in = conn.getInputStream();

            out = new FileOutputStream(fileName);

            int len;
            byte[] arr = new byte[1024 * 1000];
            while (-1 != (len = in.read(arr))) {
                out.write(arr, 0, len);
            }
            out.flush();
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.close();
                }
                if (null != in) {
                    in.close();
                }
            } catch (Exception e) {
                // do nothing
            }
        }
    }

    /**
     * 创建文件夹,如果文件夹已经存在或者创建成功返回true
     *
     * @param path
     *      路径
     * @return boolean
     */
    private static boolean createFolderIfNotExists(String path) {
        File folder = new File(path);
        if (!folder.exists()) {
            try {
                return folder.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  true;
    }

}

运行效果:

相关文章

微信公众号

最新文章

更多