【问题标题】:How to test if file exists on an SDCard?如何测试文件是否存在于 SDCard 上?
【发布时间】:2015-10-20 22:53:46
【问题描述】:

我正在尝试将 PDF 文件从我的应用程序的私人存储复制到 sd 卡,以便其他 PDF 程序可以打开它。我的问题是测试文件是否存在。如果测试 file.exists() 为真,我将不再复制该文件。问题是当条件为真时,android 会向我显示我的文件不是有效的 PDF 文件的消息

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

    InputStream in = null;
    OutputStream out = null;
    File file = new File(getFilesDir(), "ac8.pdf");

    try {
        in = assetManager.open("ac8.pdf");
        out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);

        if (file.exists()) {
            Toast.makeText(getApplicationContext(), "File already exist", Toast.LENGTH_LONG).show();
        } else {
            copyFile(in, out);
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
        }
    } catch(Exception e)
    {
        Log.e("tag", e.getMessage());               
    }

    try {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(
                Uri.parse("file://" + getFilesDir() + "/ac8.pdf"),
                "application/pdf");

        startActivity(intent);
    } catch (Exception e){
        Toast.makeText(getApplicationContext(), "No PDF application found", Toast.LENGTH_LONG).show();
    }
}

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

【问题讨论】:

    标签: android pdf input copy


    【解决方案1】:

    第三方应用无法访问您应用的 internal storage(例如,getFilesDir() 目录)。要么:

    • 将文件写入external storage,或

    • 将文件保留在内部存储中,然后通过use FileProvider 将文件通过content:// Uri 提供给第三方 PDF 查看器

    您可以在the documentation 中阅读有关第二种方法的更多信息。

    【讨论】:

    • 感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 2018-12-25
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多