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