Store pdf from assets to internal storage(private)

644 views Asked by At

In my applications i am having few pdf stored in my assests folder.Now what i want is to copy those pdfs to interal storage (private) asin (com.android.mypackage).I have written the code but seems not working.I am getting data for path not found

Code

private void CopyReadAssets() {
        AssetManager assetManager = getAssets();

        InputStream in = null;
        OutputStream out = null;
        File file = getDir("Mcq Demo", Context.MODE_PRIVATE);
        try {
            in = assetManager.open("Geography1.pdf");
            out = new BufferedOutputStream(new FileOutputStream(file));

            copyFile(in, out);
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
        } catch (Exception e) {
            Log.e("tag", e.getMessage());
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        File mcqDemo = new File(file, "Geography1.pdf");
        intent.setDataAndType(
                Uri.parse("file://" + mcqDemo),
                "application/pdf");

        startActivity(intent);
    }

    private void copyFile(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
    }
2

There are 2 answers

1
CommonsWare On

First, you are trying to write a PDF to a directory. That will not work. If you want to write a PDF to a file named Geography1.pdf, you need to do so explicitly, with a FileOutputStream pointing to such a file.

Second, your Intent will not work, as third-party apps have no access to your internal storage.

0
Hiren Patel On

Code for Copy File from assets to directory and Open file

Variables

public static final String FILE_NAME = "my_file_name";
public final static String FILE_PATH = data/data/Your_Package_Name/";   

Method

private void copyFileFromAssets() throws IOException {
    String outFileName = FILE_PATH + FILE_NAME;
    OutputStream myOutput = new FileOutputStream(outFileName);
    InputStream myInput = myContext.getAssets().open(FILE_NAME);

    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }
    myInput.close();
    myOutput.flush();
    myOutput.close();
   }

To open PDF file

Intent intent = new Intent(Intent.ACTION_VIEW);
File mcqDemo = new File(outFileName);
intent.setDataAndType(Uri.fromFile(mcqDemo), "application/pdf");
startActivity(intent);

Done