Java从网络下载图片

来源:互联网 发布:软件如何申请专利 编辑:程序博客网 时间:2024/05/22 09:38
package com.capinfo.common.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

public class Pictures {
    public static boolean downloadImage(String fromUrl, String toPath){
        try {
            URL url = new URL(fromUrl);
            File outFile = new File(toPath);
            OutputStream os = new FileOutputStream(outFile);
            InputStream is = url.openStream();
            byte[] buff = new byte[1024];
            while(true) {
                int readed = is.read(buff);
                if(readed == -1) {
                    break;
                }
                byte[] temp = new byte[readed];
                System.arraycopy(buff, 0, temp, 0, readed);
                os.write(temp);
            }
            is.close();
            os.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    public static void main(String[] args) {
        downloadImage("http://a.hiphotos.baidu.com/image/w%3D2048/sign=d37774a6a41ea8d38a227304a332314e/1ad5ad6eddc451da6146cff6b4fd5266d016327f.jpg","D:\\test\\1.txt");
    }
}

0 0
原创粉丝点击