java通过url读取网络图片
生活随笔
收集整理的這篇文章主要介紹了
java通过url读取网络图片
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用java.net讀取網絡文件
?
import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public class downimage { public void saveToFile(String destUrl) { FileOutputStream fos = null; BufferedInputStream bis = null; HttpURLConnection httpUrl = null; URL url = null; int BUFFER_SIZE = 1024; byte[] buf = new byte[BUFFER_SIZE]; int size = 0; try { url = new URL(destUrl); httpUrl = (HttpURLConnection) url.openConnection(); httpUrl.connect(); bis = new BufferedInputStream(httpUrl.getInputStream()); fos = new FileOutputStream("c:\\haha.gif"); while ((size = bis.read(buf)) != -1) { fos.write(buf, 0, size); } fos.flush(); } catch (IOException e) { } catch (ClassCastException e) { } finally { try { fos.close(); bis.close(); httpUrl.disconnect(); } catch (IOException e) { } catch (NullPointerException e) { } } } public static void main(String[] args) { // TODO Auto-generated method stub downimage dw=new downimage(); dw.saveToFile("http://10.81.36.193:8081/png.png"); } }?
注意:
如果路徑或者源文件名稱中包含特殊符號或者空格,會報505錯誤,此時需要對URL進行轉碼
ftpUrl=ftpUrl.replaceAll("%", "%25");//先將地址本身帶有的%轉為%25ftpUrl=ftpUrl.replaceAll(" ", "%20");//再將空格轉換為%20轉碼之后讀取正常。
總結
以上是生活随笔為你收集整理的java通过url读取网络图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Hi3516A开发-- UBI 文件系统
- 下一篇: (二)注册服务提供者