远程读取图片并保存

本文介绍了如何使用Apache Commons IO库来远程读取图片,并将其保存到本地。重点讲解了fileutils模块在操作过程中的应用。
摘要由CSDN通过智能技术生成
URL objUrl = new URL(url);
String tDir = System.getProperty("java.io.tmpdir"); 
String path = tDir + "tmp" + ".jpg";
File file =new File(path);
file.deleteOnExit();
FileUtils.copyURLToFile(objUrl, file);

1、fileutils使用的是apache类型common-io-x.jar

2、google guava库也能完成同样操作
Resources.asByteSource(url).copyTo(Files.asByteSink(file)); 
3、当然,你也可以通过以下方式去解决这个问题
URL url = new URL(url);
URLConnection connection = url.openConnection();
InputStream in = connection.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("downloaded.jpg"));
byte[] buf = new byte[512];
while (true) {
    int len = in.read(buf);
    if (len == -1) {
        break;
    }
    fos.write(buf, 0, len);
}
in.close();
fos.flush();
fos.close();
4、还可以通过imageio去处理
URL url = new URL(url);
BufferedImage img = ImageIO.read(url);
File file = new File("downloaded.jpg");
ImageIO.write(img, "jpg", file);





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值