站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Java 专题下载URL的内容

下载URL的内容

摘要: 下载URL的内容

</td> </tr> <tr> <td width="496" height="35" valign="top" class="ArticleTeitle"> /*
* 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 []");
}
finally { // 永远记住关闭流。
try { in.close(); out.close(); } catch (Exception e) {}
}
}
}


运行方法:

C:\java>java GetURL http://127.0.0.1:8080/zz3zcwbwebhome/ home.html

C:\java></td> <td width="188" valign="top" class="ArticleTeitle">
</td> </tr> <tr> <td height="25" colspan="2" valign="top" class="ArticleTeitle">


↑返回目录
前一篇: 时钟程序
后一篇: 菜单栏与工具条及弹出菜单