This method takes a string containing the URL of the file to be downloaded. It will create a file in the current folder whose name is the same as the remote file.
| Code Block |
|---|
def download(address)
{
def file = new FileOutputStream(address.tokenize("/")[-1])
def out = new BufferedOutputStream(file)
out << new URL(address).openStream()
out.close()
}
|
If proxy configuration is needed, call this:
| Code Block |
|---|
System.properties.putAll( ["http.proxyHost":"proxy-host", "http.proxyPort":"proxy-port","http.proxyUserName":"user-name", "http.proxyPassword":"proxy-passwd"] ) |
before the call.
Here is another approach using categories. The default left shift operators acts on text streams only. This category overrides the left shift operator making it a binary copy and uses the URL type as the source for the data.
| Code Block |
|---|
package tests.io;
class FileBinaryCategoryTest extends GroovyTestCase
{
void testDownloadBinaryFile()
{
def file = new File("logo.gif")
use (FileBinaryCategory)
{
file << "http://www.google.com/images/logo.gif".toURL()
}
assert file.length() > 0
file.delete()
}
}
class FileBinaryCategory
{
def static leftShift(File a_file, URL a_url)
{
def input
def output
try
{
input = a_url.openStream()
output = new BufferedOutputStream(new FileOutputStream(a_file))
output << input
}
finally
{
input?.close()
output?.close()
}
}
}
|