Advertisement
Guest User

Untitled

a guest
May 24th, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.26 KB | None | 0 0
  1.     public static void downloadFile(String fileURL, String saveDir)
  2.             throws IOException {
  3.         URL url = new URL(fileURL);
  4.         HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
  5.         int responseCode = httpConn.getResponseCode();
  6.  
  7.         // always check HTTP response code first
  8.         if (responseCode == HttpURLConnection.HTTP_OK) {
  9.             String fileName = "";
  10.             String disposition = httpConn.getHeaderField("Content-Disposition");
  11.             String contentType = httpConn.getContentType();
  12.             int contentLength = httpConn.getContentLength();
  13.  
  14.             if (disposition != null) {
  15.                 // extracts file name from header field
  16.                 int index = disposition.indexOf("filename=");
  17.                 if (index > 0) {
  18.                     fileName = disposition.substring(index + 10,
  19.                             disposition.length() - 1);
  20.                 }
  21.             } else {
  22.                 // extracts file name from URL
  23.                 fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
  24.                         fileURL.length());
  25.             }
  26.  
  27.             System.out.println("Content-Type = " + contentType);
  28.             System.out.println("Content-Disposition = " + disposition);
  29.             System.out.println("Content-Length = " + contentLength);
  30.             System.out.println("fileName = " + fileName);
  31.  
  32.             // opens input stream from the HTTP connection
  33.             InputStream inputStream = httpConn.getInputStream();
  34.             String saveFilePath = saveDir + File.separator + fileName;
  35.              
  36.             // opens an output stream to save into file
  37.             FileOutputStream outputStream = new FileOutputStream(saveFilePath);
  38.  
  39.             int bytesRead = -1;
  40.             byte[] buffer = new byte[BUFFER_SIZE];
  41.             while ((bytesRead = inputStream.read(buffer)) != -1) {
  42.                 outputStream.write(buffer, 0, bytesRead);
  43.             }
  44.  
  45.             outputStream.close();
  46.             inputStream.close();
  47.  
  48.             System.out.println("File downloaded");
  49.         } else {
  50.             System.out.println("No file to download. Server replied HTTP code: " + responseCode);
  51.         }
  52.         httpConn.disconnect();
  53.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement