TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
/*
* 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> |
|