Java之下載網路圖片到本地資料夾
阿新 • • 發佈:2020-11-21
核心程式碼(下載網路圖片到本地資料夾):
public class DownFileUtils { public static void downloadFile(String remoteFilePath, String localFilePath) { URL urlfile = null; HttpURLConnection httpUrl = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; File f= new File(localFilePath); try { urlfile = new URL(remoteFilePath); httpUrl = (HttpURLConnection) urlfile.openConnection(); httpUrl.connect(); bis = new BufferedInputStream(httpUrl.getInputStream()); bos = new BufferedOutputStream(newFileOutputStream(f)); int len = 2048; byte[] b = new byte[len]; while ((len = bis.read(b)) != -1) { bos.write(b, 0, len); } bos.flush(); bis.close(); httpUrl.disconnect(); } catch (Exception e) { e.printStackTrace(); }finally { try { bis.close(); bos.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { //注意這個本地資料夾(localFileMkdir)必須要指定檔案的名稱如test.jpg,否則會出現下載失敗(控制檯會報錯,訪問拒絕)。 DownFileUtils.downloadFile(networkImgUrl,localFileMkdir); // 例子 DownFileUtils.downloadFile("http://www.test.com/img/2020.jpg","D:\\test\\test.jpg"); } }