Tanas

Downloader

Jan 6th, 2015
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.83 KB | None | 0 0
  1. import java.io.BufferedInputStream;
  2. import java.io.BufferedOutputStream;
  3. import java.io.DataInputStream;
  4. import java.io.DataOutputStream;
  5. import java.io.File;
  6. import java.io.FileOutputStream;
  7. import java.io.IOException;
  8. import java.io.InputStream;
  9. import java.io.OutputStream;
  10. import java.net.MalformedURLException;
  11. import java.net.URL;
  12. import java.nio.file.Files;
  13. import java.nio.file.Paths;
  14.  
  15.  
  16. public class Downloader {
  17.     private URL url;
  18.     private byte[] buffer;
  19.    
  20.     public Downloader(String url)
  21.     {
  22.         try {
  23.             this.url = new URL(url);
  24.         } catch (MalformedURLException e) {
  25.             e.printStackTrace();
  26.         }
  27.     }
  28.  
  29.     public void download() throws IOException
  30.     {
  31.         if (this.url == null)
  32.             return;
  33.        
  34.         DataInputStream is = null;
  35.         DataOutputStream os = null;
  36.         try {
  37.             // TODO pouzijte promennou url a ziskejte z ni InputStream OK
  38.             // TODO pouzijte Buffer OK
  39.             is = new DataInputStream(url.openStream());
  40.             buffer = new byte[1024*1024];
  41.             int length = 0;
  42.            
  43.             // TODO z promenne url ziskejte jmeno souboru OK
  44.             // TODO jmeno souboru je vcetne cesty. Orezte dany string a ziskejte pouze jmeno s priponou OK
  45.             String fileName = url.getPath();
  46.             fileName = fileName.replace("/", "");
  47.             //System.out.println(fileName);
  48.            
  49.             // TODO vytvorte soubor s nazvem z promenne fileName OK
  50.             // TODO pouzijte Buffer
  51.             File file = new File(fileName);
  52.             os = new DataOutputStream(new FileOutputStream(file));
  53.            
  54.            
  55.             int c;
  56.             // TODO zapiste vsechna data z is do os. Pouzijte promennou c OK
  57. //          while ((c = is.read()) != -1) {
  58. //              os.write(c);
  59. //          }
  60.  
  61.             while ((length = is.read(buffer)) >= 0){
  62.                 os.write(buffer, 0, length);
  63.             }
  64.  
  65.  
  66.         }
  67.        
  68.         // TODO doplnte block finally kde oba streamy zavrete pokud nejsou null
  69.         finally
  70.         {
  71.             if (os != null) os.close();
  72.             if (is != null) is.close();
  73.         }
  74.     }
  75. }
Add Comment
Please, Sign In to add comment