JAVA 從網絡下載圖片保存到電腦
我嘗試了網上很多人的方法
while ((a=inputStream.read())!=-1) {//這個是大家普遍用的方法
fileOutputStream.write(b, 0, a);//這裏b是byte[],a是length
}
查了很多資料,都沒有用,最後看了一下輸入流的方法read。原來。。。。
while ((a=inputStream.read(b,0,b.length))!=-1) {//這樣子就行了
fileOutputStream.write(b, 0, a);
}
直接上代碼
- 這裏要先注意你的url是正確的圖片地址,類似.jpg或者.png之類的地址,不然怎麼改代碼都會失敗
//第一個參數是圖片的URL網絡地址,第二個是你要保存到電腦的路徑
public static void DownaloadPhoto(String url,String downaload_path){
try {
HttpURLConnection connection=(HttpURLConnection) new URL(url).openConnection();//開啓網絡
InputStream inputStream=connection.getInputStream();//獲取輸入流
FileOutputStream fileOutputStream=new FileOutputStream(new File(downaload_path));//輸出流
byte[] b=new byte[1024];
int a=0;
while ((a=inputStream.read(b,0,b.length))!=-1) {//-1就是讀取完畢的值
fileOutputStream.write(b, 0, a);//寫入數據
}
fileOutputStream.close();//記得關閉
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
博主已經試過了,是正確的代碼,也成功下載了網上的圖片
很簡單的一段代碼,但是對於我這種小白卻是一個大坑。。。
哪裏不對的歡迎大家斧正qwq。