Groovy从URL下载图片

14

我想知道从这个URL下载图像的正确方法是什么:http://www.hidemyass.com/proxy-list/img/port/7018246/1

我试过的下载方式会导致文件以未知格式保存。下面是我尝试的代码片段:

public void download(def address) {

    def file = new FileOutputStream(address.tokenize("/")[-1])
    def out = new BufferedOutputStream(file)
    out << new URL(address).openStream()
    out.close()
}
3个回答

23

这个行得通吗?我相信应该可以:

public void download(def address) {
  new File("${address.tokenize('/')[-1]}.png").withOutputStream { out ->
    out << new URL(address).openStream()
  }
}

14

谢谢Tim,我也觉得你的回答非常有帮助,只是小提醒:看起来你没有关闭URL流。我刚开始学习Groovy,听说当从闭包中退出时它会自动关闭流,因此我们可以将代码更改为:

public void download(def address) {
  new File("${address.tokenize('/')[-1]}.png").withOutputStream { out ->
      new URL(address).withInputStream { from ->  out << from; }
  }
}

4

您可以通过它们的内容类型 - URLConnection.getContentType() 或者通过字节数组获取图像类型:

content="http://www.google.ru/images/logo.png".toURL().getBytes()
ext=URLConnection.guessContentTypeFromStream(new ByteArrayInputStream(content)).replaceFirst("^image/","")
new File("logo."+ext).setBytes(content)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接