Guest User

Untitled

a guest
Nov 22nd, 2016
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. public static void downloadFile(String fileUrl)
  2. throws IOException {
  3.  
  4. String fileName = fileUrl.substring(fileUrl.lastIndexOf("/")+1);
  5.  
  6. URL url = new URL(fileUrl);
  7. InputStream is = url.openStream();
  8. FileOutputStream fos = new FileOutputStream("/Users/user/Desktop/" + fileName);
  9. int test = getFileSize(url);
  10. System.out.println(test);
  11.  
  12. byte[] buffer = new byte[4096];
  13. int bytesRead = 0;
  14.  
  15. System.out.print("Downloading " + fileName);
  16. while ((bytesRead = is.read(buffer)) != -1) {
  17. fos.write(buffer, 0, bytesRead);
  18. }
  19. System.out.print("done!");
  20. fos.close();
  21. is.close();
  22.  
  23. }
  24.  
  25. public static int getFileSize(URL url) {
  26. HttpURLConnection conn = null;
  27. try {
  28. conn = (HttpURLConnection) url.openConnection();
  29. conn.setRequestMethod("HEAD");
  30. conn.getInputStream();
  31. return conn.getContentLength();
  32. } catch (IOException e) {
  33. throw new RuntimeException(e);
  34. } finally {
  35. conn.disconnect();
  36. }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment