java下载图片到本地实例

public static void main(String[] args) {
String ImageUrl = "xxxxxxxxx";//图片url
String path="F://createVerifyCode.jpg";// 保存地址
downloadPic(ImageUrl ,path);
}


//链接url下载图片
public static boolean downloadPic(String urlList,String path) {
URL url = null;
try {
url = new URL(urlList);
DataInputStream dataInputStream = new DataInputStream(url.openStream());

FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];
int length;

while ((length = dataInputStream.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
fileOutputStream.write(output.toByteArray());
dataInputStream.close();
fileOutputStream.close();
return true;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个多线程下载图片Java 实例代码: ```java import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MultiThreadImageDownloader { public static void main(String[] args) throws Exception { String[] imageUrls = { "https://example.com/image1.jpg", "https://example.com/image2.jpg", "https://example.com/image3.jpg" }; ExecutorService executor = Executors.newFixedThreadPool(imageUrls.length); for (String imageUrl : imageUrls) { executor.execute(new ImageDownloader(imageUrl)); } executor.shutdown(); } private static class ImageDownloader implements Runnable { private String imageUrl; public ImageDownloader(String imageUrl) { this.imageUrl = imageUrl; } @Override public void run() { try { URL url = new URL(imageUrl); InputStream in = url.openStream(); FileOutputStream out = new FileOutputStream(getFileName(imageUrl)); byte[] buffer = new byte[1024]; int length = 0; while ((length = in.read(buffer)) != -1) { out.write(buffer, 0, length); } in.close(); out.close(); System.out.println("Downloaded " + imageUrl); } catch (Exception e) { System.out.println("Error downloading " + imageUrl); } } private String getFileName(String url) { int index = url.lastIndexOf("/"); return "image" + url.substring(index); } } } ``` 该程序会并发下载多张图片,并将每张图片保存到本地文件系统中。该程序使用了 Java 的线程池 ExecutorService 来管理多线程。每个任务都是一个 ImageDownloader 对象,它实现了 Runnable 接口并重写了 run() 方法。在 run() 方法中,程序会从指定的 URL 中读取图片数据,并将数据写入到本地文件中。最后,程序会输出成功下载图片的 URL。 该程序的运行结果如下: ``` Downloaded https://example.com/image1.jpg Downloaded https://example.com/image3.jpg Downloaded https://example.com/image2.jpg ``` 可以看到,三张图片都被成功下载并保存到本地文件系统中。该程序可以根据实际需要进行修改和优化,例如增加异常处理机制、设置超时时间、使用线程池等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值