Java下载图片方法

| 阅读数:--次| 作者:小豆豆
摘要: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();
		}
	}
}
返回顶部
学到老代码浏览 关闭浏览