String imageUrl = "http://example.com/image.jpg"; // 替换成你需要下载的图片URL
String savePath = "/path/to/your/save/directory/image.jpg"; // 替换成你需要保存图片的本地目录
try {
// 打开连接
URL url = new URL(imageUrl);
URLConnection connection = url.openConnection();
// 设置请求超时为5秒
connection.setConnectTimeout(5 * 1000);
// 读取数据流并保存到本地
InputStream input = connection.getInputStream();
byte[] data = new byte[2048];
int len;
FileOutputStream output = new FileOutputStream(savePath);
while ((len = input.read(data)) != -1) {
output.write(data, 0, len);
}
output.close();
input.close();
System.out.println("图片保存成功:" + savePath);
} catch (IOException e) {
e.printStackTrace();
System.out.println("图片保存失败:" + e.getMessage());
}