首页 > Java

Java下载图片方法

发表于2014-09-05 11:37:56| --次阅读| 来源webkfa| 作者小豆豆

摘要:Java下载图片方法
java代码
package com.webkfa.test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Test {
	public static void main(String[] args) throws IOException{
		downImg("http://www.baidu.com/img/bdlogo.png", "c:/", "1.png");
		System.out.println("下载完成");
	}
	/**
	 * 下载图片到其它目录
	 * @param imgUrl    http://www.baidu.com/img/bdlogo.png
	 * @param localPath    c:/
	 * @param localFileName  下载下来的别名  1.png
	 */
	public static void downImg(String imgUrl,String localPath,String localFileName){
		try {
			OutputStream os = new FileOutputStream(localPath+localFileName);
			URL uobj = new URL(imgUrl);
			HttpURLConnection httpUrl = (HttpURLConnection) uobj.openConnection();
			httpUrl.connect();
			InputStream fis = httpUrl.getInputStream();
			byte[] buf = new byte[255];
		    int len = 0;
		    while ((len = fis.read(buf)) != -1) {
		     os.write(buf, 0, len);
		    }

		    fis.close();
		    os.flush();
		    os.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

相关文章

猜你喜欢

学到老在线代码浏览器 关闭浏览
友情链接: hao123 360导航 搜狗网址导航 114啦网址导航 博客大全
Copyright © 1999-2014, WEBKFA.COM, All Rights Reserved  京ICP备14034497号-1