江左梅郎2017/02/17         
Java中的URL对象位于java.net包中,URL代表一个统一资源定位符,它是指向互联网“资源”的指针。资源可以是简单的文件或目录,也可以是对更为复杂的对象的引用,例如对数据库或搜索引擎的查询。具体使用方法大家可以参考其API。
通过URL类及其方法获取URL的内容,并将其存放如文件中,步骤如下:
1、创建一个URL对象
URL的构造方法很多,最简单的莫过于URL url = new URl(urlPath);
2、获得URL对象的各个属性,自己看API
3、使用URL来读取WWW的信息
在创建了一个URL对象之后,就可以利用它来读取资源的内容了,URL使用 openStream()方法可以获得它的输入流。
4、将读取到的内容输出
代码实现如下:
/** * 通过url路径获取内容并写到filePath文件中 * @param urlPath * @param filePath */ public static void getContentByURL(String urlPath,String filePath) { InputStream in = null; OutputStream out = null; URL url; try { //创建URL对象 url = new URL(urlPath); //获取URL输入流 in = url.openStream(); //创建输出流 out = new FileOutputStream(filePath); //将URL的内容输出到指定位置 byte[] buff = new byte[1024]; int len ; while((len = in.read(buff)) != -1){ out.write(buff,0,len); } } catch (Exception e) { e.printStackTrace(); } finally { //关闭流 if(in != null){ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if(out != null){ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
测试:
public static void main(String[] args) { String urlPath = "http://baike.baidu.com/link?url=kZRAVbsuO8jgyX2ncrRAhM6Nx9US0P61n7Fq07P-JOBS2K4bf0c2CvB5Twzo_5kPu8YMYFvFh5331fudXY9cGIoRy7daZrk4QfwKcpK1HRq"; String filePath = "F:/aa.html"; getContentByURL(urlPath,filePath); }
结果:在F盘看到指定文件,内容正确。