菜鸟修炼中,URL的两种访问方式

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();
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

饕餮幻想家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值