随笔 - 1357  文章 - 0  评论 - 1104  阅读 - 1941万

十五、从互联网获取图片且保存到指定目录

复制代码
package com.ljq.test;

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

import org.junit.Test;

/**
* 从互联网获取图片且保存到指定目录里
*
*
@author jiqinlin
*
*/
public class InternetTest {

@SuppressWarnings(
"static-access")
@Test
public void getImg() throws Exception {
String urlPath
= "http://i0.itc.cn/20101116/62d_67fd2b2a_207d_4de2_a4f9_fb93cc8da492_0.jpg";
URL url
= new URL(urlPath);
HttpURLConnection conn
= (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(
6*1000); // 注意要设置超时,设置时间不要超过10秒,避免被android系统回收
if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream inSream
= conn.getInputStream();
//把图片保存到项目的根目录
new InternetTest().readAsFile(inSream, new File("sohu.jpg"));
}

public static void readAsFile(InputStream inSream, File file) throws Exception{
FileOutputStream outStream
= new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = -1;
while( (len = inSream.read(buffer)) != -1 ){
outStream.write(buffer,
0, len);
}
outStream.close();
inSream.close();
}

}
复制代码
posted on   Ruthless  阅读(2042)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
< 2011年5月 >
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 1 2 3 4
5 6 7 8 9 10 11

点击右上角即可分享
微信分享提示