Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Image Groovy从URL下载图像_Image_Url_Groovy_Download - Fatal编程技术网

Image Groovy从URL下载图像

Image Groovy从URL下载图像,image,url,groovy,download,Image,Url,Groovy,Download,我想知道从这个RUL下载图像的正确方法是: 我试图下载它的方式使文件的格式未知。我测试的当前代码段是: public void download(def address) { def file = new FileOutputStream(address.tokenize("/")[-1]) def out = new BufferedOutputStream(file) out << new URL(address).openStream() ou

我想知道从这个RUL下载图像的正确方法是:

我试图下载它的方式使文件的格式未知。我测试的当前代码段是:

public void download(def address) {

    def file = new FileOutputStream(address.tokenize("/")[-1])
    def out = new BufferedOutputStream(file)
    out << new URL(address).openStream()
    out.close()
}
公共无效下载(def地址){
def file=new FileOutputStream(address.tokenize(“/”[-1]”)
def out=新的BufferedOutputStream(文件)

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

public void download(def address) {
  new File("${address.tokenize('/')[-1]}.png").withOutputStream { out ->
    out << new URL(address).openStream()
  }
}
公共无效下载(def地址){
新文件(${address.tokenize('/')[-1]}.png”)。withOutputStream{out->

out谢谢蒂姆,我也发现你的答案非常有用,只是一个小提示: 看起来您还没有关闭URL流。我只是从Groovy开始,我听说它在退出关闭时会关闭流,所以我们可以这样更改代码:

public void download(def address) {
  new File("${address.tokenize('/')[-1]}.png").withOutputStream { out ->
      new URL(address).withInputStream { from ->  out << from; }
  }
}
公共无效下载(def地址){
新文件(${address.tokenize('/')[-1]}.png”)。withOutputStream{out->

新URL(地址)。使用InputStream{from->out可以从其内容类型或字节数组中获取图像类型:

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