java 通过url下载图片

Dear 丶 2022-03-31 04:26 393阅读 0赞
  1. private static String Download(String urlList) {
  2. URL url = null;
  3. String filepath="";
  4. try {
  5. url = new URL(urlList);
  6. DataInputStream dataInputStream = new DataInputStream(url.openStream());
  7. String newpaht =path+getCurrentDateTime();//+"\\"+urlList.substring(urlList.lastIndexOf("/")+1, urlList.length());//+".jpg";
  8. try{
  9. File file = new File(newpaht);
  10. if(!file.exists()){
  11. file.mkdirs();
  12. }
  13. }catch(Exception ex){
  14. System.out.println(ex);
  15. }
  16. filepath=newpaht+"\\"+urlList.substring(urlList.lastIndexOf("/")+1, urlList.length())+".jpg";
  17. FileOutputStream fileOutputStream = new FileOutputStream(new File(filepath));
  18. ByteArrayOutputStream output = new ByteArrayOutputStream();
  19. byte[] buffer = new byte[1024];
  20. int length;
  21. while ((length = dataInputStream.read(buffer)) > 0) {
  22. output.write(buffer, 0, length);
  23. }
  24. fileOutputStream.write(output.toByteArray());
  25. dataInputStream.close();
  26. fileOutputStream.close();
  27. } catch (MalformedURLException e) {
  28. e.printStackTrace();
  29. } catch (IOException e) {
  30. e.printStackTrace();
  31. }
  32. return filepath;
  33. }

测试

  1. public static void main(String[] args) {
  2. String url = "https://img.zcool.cn/community/01f9ea56e282836ac72531cbe0233b.jpg";
  3. Download(url);
  4. }

引用

  1. import java.io.ByteArrayOutputStream;
  2. import java.io.DataInputStream;
  3. import java.io.File;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.net.MalformedURLException;
  7. import java.net.URL;

发表评论

表情:
评论列表 (有 0 条评论,393人围观)

还没有评论,来说两句吧...

相关阅读