Groovy从URL下载图像

时间:2011-01-12 22:58:12

标签: image url groovy download

我想知道从这个RUL下载图像的正确方法是: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 个答案:

答案 0 :(得分:19)

这有用吗?我相信它应该:

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

答案 1 :(得分:9)

谢谢蒂姆,我也发现你的答案很有帮助,只是小记: 看起来您还没有关闭网址流。我刚开始使用Groovy,我听说它在关闭时关闭了,所以我们可以更改代码:

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

答案 2 :(得分:2)

您可以从其内容类型 - 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)