Advertisement
Guest User

Untitled

a guest
Sep 5th, 2011
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. public void download(String address, String localFileName, String saveTo) {
  2. OutputStream out = null;
  3. URLConnection conn = null;
  4. InputStream in = null;
  5. try {
  6. File f = new File(saveTo + localFileName);
  7. f.createNewFile();
  8. URL url = new URL(address);
  9. out = new BufferedOutputStream(new FileOutputStream(saveTo + localFileName));
  10. conn = url.openConnection();
  11. in = conn.getInputStream();
  12. byte[] buffer = new byte[1024];
  13. int numRead;
  14. long numWritten = 0;
  15. int length = conn.getContentLength();
  16.  
  17.  
  18. long startTime = System.currentTimeMillis();
  19.  
  20.  
  21. while ((numRead = in.read(buffer)) != -1)
  22. {
  23. int percentage = (int)(((double)numWritten / (double)length) * 100D);
  24.  
  25. //percentage.. need estimated time..
  26. out.write(buffer, 0, numRead);
  27. numWritten += numRead;
  28.  
  29.  
  30. long timeElapsed = System.currentTimeMillis() - startTime;
  31. double avgSpeed = (double) numWritten / timeElapsed;
  32. double timeLeft = (length - numWritten) / avgSpeed;
  33. System.out.println("Milliseconds until download finishes: " + timeLeft);
  34.  
  35.  
  36. }
  37. } catch (Exception exception) {
  38. exception.printStackTrace();
  39. } finally {
  40. try {
  41. if (in != null) {
  42. in.close();
  43. }
  44. if (out != null) {
  45. out.close();
  46. }
  47. } catch (IOException ioe) {
  48. }
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement