java 通过http下载文件并保存到本地自定义路径

调用downLoadFromUrl方法,三个String类型的参数,简单好用

public static void  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{
    URL url = new URL(urlStr);
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    //设置超时间
    conn.setConnectTimeout(10*1000);
    //设置一个请求头
    conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
    //获得输入流
    InputStream inputStream = conn.getInputStream();
    //获取数组
    byte[] getData = readInputStream(inputStream);
    //文件保存路径
    File saveDir = new File(savePath);
    if(!saveDir.exists()){
        saveDir.mkdir();
    }
    File file = new File(saveDir+File.separator+fileName);
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(getData);
    if(null != fos){
        fos.close();
    }
    if(null != inputStream){
        inputStream.close();
    }


    System.out.println("info:"+url+" download success");

}

public static  byte[] readInputStream(InputStream inputStream) throws IOException {
    byte[] buffer = new byte[1024];
    int len = 0;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    while((len = inputStream.read(buffer)) != -1) {
        bos.write(buffer, 0, len);
    }
    bos.close();
    return bos.toByteArray();
}
经验分享 程序员 微信小程序 职场和发展