Java 获取网络url图片返回file文件对象

导入包:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 *   测试
 */
public static void main(String[] args) {
   try {
        String destUrl = "https://ibsbjstar.ccb.com.cn/NCCB_Encoder/Encoder?CODE=EUSo4Twu6YRk2JDPJ9OnpfgrdDObpGwKBGOTqVwnBfWAvjCP5UOFuig6hySmrww2hXVIqDgb5NUOrvwI5NRuqtQ3pXcRVh";
        HttpURLConnection httpUrl = (HttpURLConnection) new URL(destUrl).openConnection();
        httpUrl.connect();
        File file = FileUtil.inputStreamToFile(httpUrl.getInputStream(),"url.png");
        System.out.println("111====>>>>"+file.getPath());
        httpUrl.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
}


/**
 *   工具类
 * inputStream 转 File
 */
public static File inputStreamToFile(InputStream ins, String name) throws Exception{
    File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);
    if (file.exists()) {
        return file;
    }
    OutputStream os = new FileOutputStream(file);
    int bytesRead;
    int len = 8192;
    byte[] buffer = new byte[len];
    while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
        os.write(buffer, 0, bytesRead);
    }
    os.close();
    ins.close();
    return file;
}

打印输出:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值