package com.bzu.url;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
public class URLDemo {
/**URL两种访问方式:
* 1.openConnection()
* 2.openStream()
* @param args
*/
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("请输入要下载的地址:");
String urlString=input.nextLine();
System.out.println("请输入新的名字:");
String fileName=input.nextLine();
System.out.println("请输入本地存储的地址:");
String savePath=input.nextLine();
if(urlString!=null&&fileName!=null&&savePath!=null){
try {
DownLoadUtil.download(urlString, fileName, savePath);
// DownLoadUtil.download("http://pic.yesky.com/uploadImages/2014/345/35/228TSWE5QQU9.jpg", "mm2.jpg", "e:\\zhaosi");
// DownLoadUtil.download("http://h.hiphotos.baidu.com/image/h%3D200/sign=55cc9c48f6d3572c79e29bdcba126352/e850352ac65c10380c5e0563b6119313b07e896b.jpg", "MM.jpg", "e:\\zhaosi");
System.out.println("下载成功!");
} catch (IOException e) {
e.printStackTrace();
}
}else{
System.out.println("输入有误!");
}
}
}
//新建一个从网络上下载图片的工具类
class DownLoadUtil{
public static void download(String urlString,String fileName,
String savePath) throws IOException{
URL url=new URL(urlString);//根据 String 表示形式创建 URL 对象。
//返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。方式1
// URLConnection conn=url.openConnection();
// //返回从此打开的连接读取的输入流。
// InputStream is=conn.getInputStream();
InputStream is=url.openStream();//方式2
byte [] buff=new byte[1024];//创建一个缓冲区
int len=0;//读取数量
File file=new File(savePath);
if(!file.exists()){//如果不存在
file.mkdirs();//创建文件
}
//创建一个向指定 File 对象表示的文件中写入数据的文件输出流。
OutputStream os=new FileOutputStream(
//返回此抽象路径名的绝对路径名字符串+\\+新文件名
file.getAbsolutePath()+"\\"+fileName);
while((len=is.read(buff))!=-1){
os.write(buff, 0, len);//往指定文件中写入数据
}
//释放资源
os.close();
is.close();
}
}
菜鸟修炼中,URL的两种访问方式
最新推荐文章于 2021-06-30 23:50:32 发布