Search code examples
androidfilesd-card

Copying a file to sdcard


I'm desperately trying to copy a file to the sdcard from my raw folder, but it won't work! The file just doesn't show up in the file manager, and the program I give the path to (via an intent) can't find it either. This is what I'm trying...

private void CopyAssets() throws IOException {
        String path = Environment.getExternalStorageDirectory() + "/jazz.pdf";
        InputStream in = getResources().openRawResource(R.raw.jazz);
        FileOutputStream out = new FileOutputStream(path);
        byte[] buff = new byte[1024];
        int read = 0;
    try {
       while ((read = in.read(buff)) > 0) {
          out.write(buff, 0, read);
       }
    } finally {
         in.close();

         out.close();
    }
}

After which I try...

    try {
        CopyAssets();

    } catch (IOException e1) {
        e1.printStackTrace();
    }

    String aux = Environment.getExternalStorageDirectory() + "/jazz.pdf";

    Uri path = Uri.parse(aux);

    Intent intent = new Intent(Intent.ACTION_VIEW);

    intent.setDataAndType(path, "application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    try {

        startActivity(intent);

    } catch (ActivityNotFoundException e) {

        Toast.makeText(bgn1.this, "No Application Available to View PDF",
                Toast.LENGTH_SHORT).show();
    }

Solution

  • Just write out.flush(); in finally block and let me know what happen,

    finally {
           out.flush();
           in.close();
           out.close();
          }
    

    Update:

    Working code:

    private void CopyAssets() throws IOException
    {       
        InputStream myInput = getResources().openRawResource(R.raw.jazz);
        String outFileName = Environment.getExternalStorageDirectory() + "/jazz.pdf";
        OutputStream myOutput = new FileOutputStream(outFileName);
        // transfer bytes from the input file to the output file
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0)
        {
            myOutput.write(buffer, 0, length);
        }
        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
      }
    }