Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Download a file programatically

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 56
    Comment on it

    In Android we can download a file from a given url so that we can use that file's data without downloading again and again so we save that file in internal or external storage of device.

    you can use this method to download your file, you have to pass url and file object.

    Here URLConnection class provide access to obtain connection on the specified url. After making connection to that url you can get length of response coming from url.

    Then you have to read the bytes coming from url and then write that bytes on a file by using Data output stream write method like this :

    private static void fileDownloaderMethod(String yourUrl, File file) {
      try {
          URL newUrl = new URL(yourUrl);
          URLConnection urlConnection = newUrl.openConnection();
          int length = urlConnection.getContentLength();
    
      DataInputStream stream = new DataInputStream(newUrl.openStream());
    
        byte[] buffer = new byte[length];
        stream.readFully(buffer);
        stream.close();
    
        DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream(file));
        dataOutputStream.write(buffer);
        dataOutputStream.flush();
        dataOutputStream.close();}
     catch(FileNotFoundException e) {
          return;
      } catch (IOException e) {
          return;
      }}
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: