2

I have a Groovy script where I am downloading a file from a url to my local machine like so..

URL url = new URL("http://i.imgur.com/pszAeGh.png")
HttpURLConnection urlConn =  url.openConnection()
File pic = new File('/Users/me/Downloads', 'myimage.jpg')
pic.append(urlConn.getInputStream())

If the 'myimage.jpg' doesn't exist in the Downloads folder, I want the script to create it. How can I specify that? Right now the 3rd line gives

java.io.FileNotFoundException: /Users/me/Downloads/myimage.jpg (No such file or directory)

Some other posts for Java have suggested using the createNewFile method but Groovy is failing even when it tries to create the file.

Community
  • 1
  • 1
AbuMariam
  • 3,282
  • 13
  • 49
  • 82

1 Answers1

6

You should just be able to do:

new File('/Users/me/Downloads', 'myImage.gif').withOutputStream { os ->
    os << new URL("http://i.imgur.com/pszAeGh.png").openStream()
}

Assuming /Users/me/Downloads exists

tim_yates
  • 167,322
  • 27
  • 342
  • 338