Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.nio.file.Files;
- import java.nio.file.StandardCopyOption;
- import java.util.concurrent.TimeUnit;
- public class TwoFileDownloadingWithJoin {
- public static void main(String[] args) {
- Thread beatPrinter = new BeatPrinter();
- Thread down1 = new FileDownloader("https://goo.gl/nqZJn4", "meet1.jpg");
- Thread down2 = new FileDownloader("https://goo.gl/UoSMMt", "meet2.jpg");
- beatPrinter.setName("Beat Printer");
- down1.setName("file1 downloader");
- down2.setName("file2 downloader");
- try {
- down1.start();
- down2.start();
- TimeUnit.MILLISECONDS.sleep(100);
- beatPrinter.start();
- down1.join();
- down2.join();
- ((BeatPrinter) beatPrinter).kill();
- beatPrinter.join();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("Download Complete");
- }
- }
- class BeatPrinter extends Thread {
- private volatile boolean live = true;
- @Override
- public void run() {
- while (live) {
- printStar("Downloading ");
- }
- }
- void kill() {
- live = false;
- }
- private void printStar(String msg) {
- System.out.print(msg);
- char[] signs = {'-', '\\', '|', '/'};
- for (char s : signs) {
- System.out.print(s);
- try {
- Thread.sleep(300);
- System.out.print('\b');
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- for (int i = 0; i < msg.length(); i++)
- System.out.print('\b');
- }
- }
- class FileDownloader extends Thread {
- private String url;
- private String fileName;
- FileDownloader(String url, String fileName) {
- this.url = url;
- this.fileName = fileName;
- }
- @Override
- public void run() {
- File destinationFile = new File(fileName);
- try {
- System.out.println("Starting download of " + fileName);
- URL fileUrl = new URL(url);
- HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection();
- if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
- InputStream inputStream = connection.getInputStream();
- Files.copy(inputStream, destinationFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
- inputStream.close();
- } else {
- System.out.println("Error: " + connection.getResponseMessage());
- }
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement