Created
May 22, 2012 19:43
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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