题目地址:https://www.icourse163.org/learn/PKU-1001941004?tid=1450230441#/learn/hw?id=1222245416
下面的程序可以下载多个网页文件(download方法已写好),请将它改成多线程进行下载(评分占7分),如果可能, 显示计算全部下载完成程序所用的时间(提示:new Date().getTime()可以得到当前时间的毫秒数,评分占3分)。另外,请注意一下,
系统中http:传到平台后,它自动改成了https:,所以请改回http:。 另外,有一些链接访问不了,所以要注意加try...catch。
import java.net.URL;
import java.io.*;
class Downloader
{
public static void main(String[] args)
throws Exception
{
final URL[] urls = {
new URL("https://www.pku.edu.cn"),
new URL("https://www.baidu.com"),
new URL("https://www.sina.com.cn"),
new URL("https://www.dstang.com")
};
final String[] files = {
"pku.htm",
"baidu.htm",
"sina.htm",
"study.htm",
};
for(int idx=0; idx<urls.length; idx++){
try{
System.out.println( urls[idx] );
download( urls[idx], files[idx]);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
static void download( URL url, String file)
throws IOException
{
try(InputStream input = url.openStream();
OutputStream output = new FileOutputStream(file))
{
byte[] data = new byte[1024];
int length;
while((length=input.read(data))!=-1){
output.write(data,0,length);
}
}
}
}
解答如下:
package week8;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Date;
public class task1 {
public static void main(String[] args) throws Exception
{
// TODO Auto-generated method stub
final URL[] urls = {
new URL("http://www.pku.edu.cn"),
new URL("http://www.baidu.com"),
new URL("http://www.sina.com.cn"),
new URL("http://www.dstang.com")
};
final String[] files = {
"pku.htm",
"baidu.htm",
"sina.htm",
"study.htm",
};
Thread [] threadPool = new Thread[urls.length];
DownloadWeb [] downloadWeb = new DownloadWeb[urls.length];
for(int i=0; i<urls.length; i++)
{
System.out.println( urls[i] );
downloadWeb[i] = new DownloadWeb(urls[i],files[i]);
threadPool[i] = new Thread(downloadWeb[i]);
threadPool[i].run();
}
}
}
class DownloadWeb implements Runnable
{
URL url;
String file;
DownloadWeb(URL url, String file)
{
this.url = url;
this.file = file;
}
public void run()
{
long temp = new Date().getTime();
try
{
download(this.url, this.file);
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.printf("下载%s失败\n", file);
}
System.out.printf("下载%s花了%dl毫秒\n", file, new Date().getTime() - temp); //long的占位符居然是dl,郁闷死
}
private void download( URL url, String file) throws IOException
{
try(InputStream input = url.openStream();
OutputStream output = new FileOutputStream(file))
{
byte[] data = new byte[1024];
int length;
while((length=input.read(data))!=-1)
{
output.write(data,0,length);
}
}
}
}