正文

下载URL的内容2006-05-09 16:09:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/sword2008/13785.html

分享到:

/*  * Copyright (c) 2000 David Flanagan.  All rights reserved.  * This code is from the book Java Examples in a Nutshell, 2nd Edition.  * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.  * You may study, use, and modify it for any non-commercial purpose.  * You may distribute it non-commercially as long as you retain this notice.  * For a commercial use license, or to purchase the book (recommended),  * visit http://www.davidflanagan.com/javaexamples2.  */ import java.io.*; import java.net.*; /**  *  这个简单的程序使用URL及其openStream()方法下载  *  URL内容并复制到文件或后台。  **/ public class GetURL {     public static void main(String[] args) {         InputStream in = null;            OutputStream out = null;         try {             // 检测参数             if ((args.length != 1)&& (args.length != 2))                  throw new IllegalArgumentException("Wrong number of args");                  // 设置流             URL url = new URL(args[0]);   //创建URL             in = url.openStream();        // 打开一个流             if (args.length == 2)         // 获取相应的输出流                 out = new FileOutputStream(args[1]);             else out = System.out;                  // 从URL复制字节到输出流             byte[] buffer = new byte[4096];             int bytes_read;             while((bytes_read = in.read(buffer)) != -1)                 out.write(buffer, 0, bytes_read); }         // On exceptions, print error message and usage message.         catch (Exception e) {             System.err.println(e);             System.err.println("Usage: java GetURL <URL> [<filename>]");         }         finally {  // 永远记住关闭流。             try { in.close();  out.close(); } catch (Exception e) {}         }     } } 运行方法: C:\java>java     GetURL  http://127.0.0.1:8080/zz3zcwbwebhome/     home.html C:\java> 来源: java实例 中国电力出版社

阅读(5045) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册