将pdf从资产存储到内部存储(私有)

时间:2015-06-10 11:46:44

标签: android storage

在我的应用程序中,我在我的assests文件夹中存储的pdf很少。现在我想要的是将这些pdf复制到内部存储(私有)asin(com.android.mypackage)。我已编写代码但似乎无法正常工作。我正在获取未找到路径的数据

代码

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 个答案:

答案 0 :(得分:1)

首先,您尝试将PDF写入目录。那样不行。如果要将PDF写入名为Geography1.pdf的文件,则需要明确地执行此操作,并使用FileOutputStream指向此类文件。

其次,由于第三方应用无权访问您的内部存储空间,因此Intent无效。

答案 1 :(得分:0)

复制文件的代码从资产目录并打开文件

<强>变量

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

方式

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();
   }

打开 PDF文件

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

完成