java读取本地文件大家都不陌生,而且实现也相对轻松。java读取远程文件怎么实现呢?
使用到的Java的核心类:java.net.URL,java.net.URLConnection,java.net.HttpURLConnection
原理:
(1)使用文件地址创建URL,如
URLurl = new URL(url)
(2)创建url连接,如:URLConnection urlconn=url.openConnection()
(3)转化url连接为httpUrl连接,如:HttpURLConnection httpconn = (HttpURLConnection) urlconn;
(4)读取httpconn的流,如httpconn.getInputStream()或
缓存读取流:BufferedInputStream bis=new BufferedInputStream(httpconn.getInputStream());
(5).读到byte数组,如:while((r=bis.read(b))>0);
扫描二维码关注公众号,回复:
799414 查看本文章
总结:最大的感受就是网络读取文件和本地读取的区别。本地文件就是file,而网络上文件是一个URL。这是我自己的理解,可能有点误解吧。
ps一下代码:
import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class FileDownload { public static void main(String[] args) throws IOException { //String remote_img_url="http://zhbccrm.xicp.net:8008/v1/tfs/T1WaJTByxT1R4cSCrK.png"; String remote_img_url="http://img.baidu.com/img/iknow/sula201506/baiduzhidaowenkugaokao.png?t=1433819530"; URL url=null; URLConnection urlconn=null; HttpURLConnection httpconn=null; BufferedInputStream bis=null; try { url = new URL(remote_img_url); urlconn = url.openConnection(); //1.5以后URLConnection设置连接超时,从主机读取数据超时 单位:毫秒 /*urlconn.setConnectTimeout(10000); urlconn.setReadTimeout(20000);*/ httpconn = (HttpURLConnection) urlconn; int httpResult = httpconn.getResponseCode(); System.out.println("httpResult::"+httpResult); if(httpResult==HttpURLConnection.HTTP_OK){ int filesize = urlconn.getContentLength(); // 取数据长度 byte[] b=new byte[filesize]; bis=new BufferedInputStream(httpconn.getInputStream()); int r=0; while((r=bis.read(b))>0); System.out.println("length::"+filesize); //System.out.println("string:"+new String(b,"UTF-8")); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ if(httpconn!=null) httpconn.disconnect(); if(bis!=null){ bis.close(); } } } }
总结:使用httpClient实现远程访问服务,怎么判断