Advertisement
Guest User

Untitled

a guest
Dec 30th, 2019
11
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.21 KB | None | 0 0
  1. package com.simple.connection;
  2.  
  3. import java.io.BufferedInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.net.URL;
  8. import java.net.URLConnection;
  9.  
  10. public class Example1 {
  11.     public static final String ADDRESS = "http://fullhdwall.com/wp-content/uploads/2016/11/Yellow-New-Year-Background.jpg";
  12.     public static final String TARGET_FILE = "Foo.jpg";
  13.  
  14.     public static void main(String[] args) throws IOException {
  15.         byte[] target;
  16.         long before = System.nanoTime();
  17.         URLConnection conn = new URL(ADDRESS).openConnection();
  18.         try (InputStream is = new BufferedInputStream(conn.getInputStream());
  19.              FileOutputStream fileOutputStream = new FileOutputStream(TARGET_FILE)) {
  20.             target = new byte[conn.getContentLength()];
  21.             int bytesRead;
  22.             while ((bytesRead = is.read(target, 0, target.length)) != -1) {
  23.                 fileOutputStream.write(target, 0, bytesRead);
  24.             }
  25.         }
  26.         long after = System.nanoTime();
  27.         System.out.println("Download time: " + ((after - before)/1e6) + "ms");
  28.         System.out.println("Total: " + target.length/1024 + "kB");
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement