Last active
July 1, 2018 10:49
-
-
Save tankala/29e8c7f9be175bfc2dd8f1720e0b7bcb to your computer and use it in GitHub Desktop.
Downloading 2 avatars in parallel at a time in Java
This file contains hidden or 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
import java.util.Arrays; | |
import java.util.List; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.ThreadPoolExecutor; | |
import java.io.InputStream; | |
import java.net.URL; | |
import java.nio.file.Files; | |
import java.nio.file.Paths; | |
import java.nio.file.StandardCopyOption; | |
public class Test { | |
public static void main(String[] args) { | |
ThreadPoolExecutor executor = (ThreadPoolExecutor)Executors.newFixedThreadPool(2); | |
List<String> avatarsNames = Arrays.asList("1.png","2.png","3.png","4.png","5.png","6.png","7.png","8.png","9.png","10.png"); | |
avatarsNames.forEach(avatarName -> executor.submit(() -> { | |
getAndStoreAvatar(avatarName); | |
return null; | |
})); | |
System.out.println("Files Download in process"); | |
executor.shutdown(); | |
} | |
private static void getAndStoreAvatar(String avatarName) { | |
try { | |
URL avataUrl = new URL("https://api.adorable.io/avatars/285/" + avatarName); | |
System.out.println(avatarName + " is downloading"); | |
try(InputStream in = avataUrl.openStream()) { | |
Files.copy(in, Paths.get(avatarName), StandardCopyOption.REPLACE_EXISTING); | |
} | |
} catch(Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment