URL类的使用(用来下载网络资源)

package ip;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class studnetURL {

private static URL url = null;
private String toPath = null;


public void getURL(String spec) throws MalformedURLException {
url = new URL(spec);
}

public void getURL(String protocol ,String hostName, String file) throws MalformedURLException {
url = new URL(protocol ,hostName,file);
}

public void getURL(String protocol, String hostName, int port, String file) throws MalformedURLException {
url = new URL(protocol, hostName, port, file);
}

public void readURLFileToLocalhost(String toPath) {
panDuanToPathExists(new File(toPath));
this.toPath = toPath;
getURLFileToLocalhost();
}
/*]
* 判断保存网络文件的目录是否存在,不存在就创建
*/
private void panDuanToPathExists(File toPath) {
if(!toPath.exists()) {
toPath.mkdirs();
}
}
private void getURLFileToLocalhost() {
InputStreamReader isr = null;
FileWriter fw = null;
PrintWriter pw = null;
try {
String urlFileName = getUrlFileName(); //取得保存文件的名字
isr = new InputStreamReader(url.openStream());
fw = new FileWriter(new File(this.toPath).getPath()+"/"+urlFileName);
pw = new PrintWriter(fw);
int data = -1;
while((data = isr.read()) != -1) {
pw.write(data);
pw.flush();
}
pw.close();
fw.close();
isr.close();
} catch(IOException ioe) {
}
}

private String getUrlFileName() throws IOException {
if(url.getProtocol().equals("file")) {
return new File(url.getFile()).getName();
}
if(url.getProtocol().equals("http")) {
URLConnection urlConnection = url.openConnection();
String url = urlConnection.getURL().toString();
return url.substring(url.indexOf(".")+1)+".html";
}
return "www.txt";
}
public static void main(String [] args) throws IOException {
studnetURL urls = new studnetURL();
urls.getURL("http://www.hao123.com");
urls.readURLFileToLocalhost("D:/URl/content/");
urls.getUrlFileName();
//System.out.println(url.getPort());

}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值