Search code examples
androiddownloadandroid-download-manager

In Android is it possible to download any file from server directly to /data/data/ path of app?


I want to download a file from server directly to data/data/ path of my application. Currently I am downloading the file using download manager at external storage. Could you please suggest if there is any way to directly download to data/data/ path of application.

Just to add, Android's default DownloadManager does not provide any option to do this.

Thanks in Advance


Solution

  • Algorithm is as follows

    1. Create an AsyncTask File

    2. Connect to the server Using httpGet or Post

    3. Store the Response to the data/data/packagename/mydownload`

      The below code may help you.

      fileName = fileName.replaceAll("[^a-zA-Z0-9- _,()]+","")+ ".(your format example PDF)";
      
          client = new DefaultHttpClient();
      
              request = new HttpGet(URL);
      
      
      
          response = client.execute(request);
      
      
      
          HttpEntity entity = response.getEntity();
          String PATH = "/data/data/" + context.getPackageName() + "/mydownload/";
          File file = new File(PATH);
          file.mkdirs();
      
      
      
          final long lenghtOfFile = entity.getContentLength();
          File outputFile = new File(file, fileName);
      
          Log.i("length",lenghtOfFile +fileName);
          //if(outputFile.exists())   {
          FileOutputStream fos = new FileOutputStream(outputFile);
      
          InputStream  is = entity.getContent();
      
      
      
          byte[] buffer = new byte[1024];
          int len1 = 0;
          long total = 0;
      
      
          while ((len1 = is.read(buffer)) != -1) {
              fos.write(buffer, 0, len1); 
      
              }
      
          }
          fos.close();
          is.close();