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();
}
}
 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM