Skip to content

Instantly share code, notes, and snippets.

@soldev-42
Created November 26, 2015 18:02
Show Gist options
  • Select an option

  • Save soldev-42/a975d6c406cd83e966fc to your computer and use it in GitHub Desktop.

Select an option

Save soldev-42/a975d6c406cd83e966fc to your computer and use it in GitHub Desktop.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
public class FileDownloader
{
/**
* Creates temporary path
*
* @return String
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
*/
protected static String getDestinationPath()
{
String storageDirectory = System.getProperty("user.dir").concat(File.separator).concat("storage");
File tempDirectory = new File(storageDirectory);
if (!tempDirectory.exists()) {
tempDirectory.mkdirs();
}
String temporaryFileName = UUID.randomUUID().toString();
return storageDirectory.concat(File.separator).concat(temporaryFileName);
}
/**
* Downloads external URL to destination path
* Returns local path to downloaded URL
*
* @param fileUrl
* @return String
* @throws IOException
* @throws NoSuchAlgorithmException
*/
public static String download(String fileUrl) throws IOException, NoSuchAlgorithmException
{
return download(fileUrl, "");
}
/**
* Downloads external URL to destination path
* Returns local path to downloaded URL
*
* @param fileUrl
* @return String
* @throws IOException
* @throws NoSuchAlgorithmException
*/
public static String download(String fileUrl, String extension) throws IOException, NoSuchAlgorithmException
{
String destinationPath = getDestinationPath().concat(extension.length()>0 ? "." : "").concat(extension);
ReadableByteChannel readableByteChannel = Channels.newChannel((new URL(fileUrl)).openStream());
FileOutputStream fileOutputStream = new FileOutputStream(destinationPath);
fileOutputStream.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
readableByteChannel.close();
fileOutputStream.close();
return destinationPath;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment