Java讀取并下載網(wǎng)絡(luò)文件的方法
更新時(shí)間:2017年08月21日 10:26:59 作者:Marydon
這篇文章主要為大家詳細(xì)介紹了Java讀取并下載網(wǎng)絡(luò)文件的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
本文實(shí)例為大家分享了Java讀取并下載網(wǎng)絡(luò)文件的具體代碼,供大家參考,具體內(nèi)容如下
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * Java讀取并下載網(wǎng)絡(luò)文件 * @author Marydon * @createTime 2017年8月18日下午5:24:09 * @updateTime * @Email:marydon2017@163.com * @version:1.0.0 * @referenceLink * <a > java 從網(wǎng)絡(luò)Url中下載文件</a> */ public class DownloadFromNetwork { /** * 從網(wǎng)絡(luò)Url中下載文件 * @param urlStr * @param fileName * @param savePath * @throws IOException */ public static void downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{ URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); //設(shè)置超時(shí)間為3秒 conn.setConnectTimeout(3*1000); //防止屏蔽程序抓取而返回403錯(cuò)誤 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //得到輸入流 InputStream inputStream = conn.getInputStream(); //獲取自己數(shù)組 byte[] getData = readInputStream(inputStream); //文件保存位置 File saveDir = new File(savePath); if(!saveDir.exists()){ saveDir.mkdirs(); } File file = new File(saveDir+File.separator+fileName); FileOutputStream fos = new FileOutputStream(file); fos.write(getData); if(fos!=null){ fos.close(); } if(inputStream!=null){ inputStream.close(); } System.out.println("info:"+url+" download success"); } /** * 從輸入流中獲取字節(jié)數(shù)組 * @param inputStream * @return * @throws IOException */ 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(); } public static void main(String[] args) { try{ for (int i = 201; i <=520; i++) { downLoadFromUrl("https://ss1.bdstatic.com/kvoZeXSm1A5BphGlnYG/skin/" + i + ".jpg",i + ".jpg","E:/Downloads/wallpaper/baiduSkin"); } }catch (Exception e) { // TODO: handle exception } } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot通過token實(shí)現(xiàn)用戶互踢功能(具體實(shí)現(xiàn))
所謂token,既用戶能夠在一定時(shí)間內(nèi)證明自己身份的一長(zhǎng)串字符串,這篇文章主要介紹了SpringBoot通過token實(shí)現(xiàn)用戶互踢功能,需要的朋友可以參考下2024-04-04Java使用注解實(shí)現(xiàn)防止重復(fù)提交實(shí)例
這篇文章主要介紹了Java使用注解實(shí)現(xiàn)防止重復(fù)提交實(shí)例,在一些項(xiàng)目中由于用戶誤操作,多次點(diǎn)擊表單提交按鈕,會(huì)產(chǎn)生很多次的數(shù)據(jù)交互,為了解決這一問題,本文使用注解來實(shí)現(xiàn)防止重復(fù)提交,需要的朋友可以參考下2023-07-07Java如何利用Socket進(jìn)行數(shù)據(jù)讀寫
這篇文章主要介紹了Java如何利用Socket進(jìn)行數(shù)據(jù)讀寫,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10