Java下载图片方法

| 803次阅读| 作者:小豆豆
摘要:Java下载图片方法
java代码
01package com.webkfa.test;
02 
03import java.io.FileOutputStream;
04import java.io.IOException;
05import java.io.InputStream;
06import java.io.OutputStream;
07import java.net.HttpURLConnection;
08import java.net.URL;
09public class Test {
10    public static void main(String[] args) throws IOException{
11        downImg("http://www.baidu.com/img/bdlogo.png", "c:/", "1.png");
12        System.out.println("下载完成");
13    }
14    /**
15     * 下载图片到其它目录
16     * @param imgUrl    http://www.baidu.com/img/bdlogo.png
17     * @param localPath    c:/
18     * @param localFileName  下载下来的别名  1.png
19     */
20    public static void downImg(String imgUrl,String localPath,String localFileName){
21        try {
22            OutputStream os = new FileOutputStream(localPath+localFileName);
23            URL uobj = new URL(imgUrl);
24            HttpURLConnection httpUrl = (HttpURLConnection) uobj.openConnection();
25            httpUrl.connect();
26            InputStream fis = httpUrl.getInputStream();
27            byte[] buf = new byte[255];
28            int len = 0;
29            while ((len = fis.read(buf)) != -1) {
30             os.write(buf, 0, len);
31            }
32 
33            fis.close();
34            os.flush();
35            os.close();
36        } catch (Exception e) {
37            // TODO Auto-generated catch block
38            e.printStackTrace();
39        }
40    }
41}
返回顶部
学到老代码浏览 关闭浏览