Skip to content

Instantly share code, notes, and snippets.

@mcenirm
Created May 22, 2012 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcenirm/2771175 to your computer and use it in GitHub Desktop.
Save mcenirm/2771175 to your computer and use it in GitHub Desktop.
Download a resource from a URL and save as a file in the current directory
/**
* Download a resource from a URL and save as a file in the current directory.
* (no overwrite, no timestamp checking, assumes URL has a sensible filename-like path)
*/
File grabRemoteUrlAsLocalFile(String remote) throws MalformedURLException, IOException {
URL remoteUrl = new URL(remote);
String localName = url2filename(remoteUrl);
File localFile = new File(localName);
Path localPath = localFile.toPath();
if (!localFile.exists()) {
try (InputStream in = remoteUrl.openStream()) {
Files.copy(in, localPath);
}
}
return localFile;
}
String url2filename(URL theUrl) {
String path = theUrl.getPath();
File file = new File(path);
String name = file.getName();
return name;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment