JAVA快速获取网络图片或者URL图片并保存到本地

JAVA快速获取网络图片或者URL图片并保存到本地,直接上代码:

 


package com.xh.service;

import org.springframework.stereotype.Service;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

@Service
public class ImageService {

public void getImg(String u, String saveFile) {
URL url;
try {
url = new URL(u);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream in = conn.getInputStream();
byte[] data = readInputStream(in);
File f = new File(saveFile);
FileOutputStream out = new FileOutputStream(f);
out.write(data);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}

private byte[] readInputStream(InputStream ins) throws IOException {

ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = ins.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
ins.close();
return out.toByteArray();
}
}
 

 

posted @ 2021-06-04 14:57  XUEZHAOCHANG  阅读(1186)  评论(0编辑  收藏  举报