【问题标题】:Get filename and path from uri for a text file从 uri 获取文本文件的文件名和路径
【发布时间】:2013-12-08 21:04:00
【问题描述】:

我有一个应用程序,它应该能够打开和读取电子邮件中的文本文件。 我将清单更改为以下

<activity 
android:name="FileLoaderActivity"
    android:label="@string/fileloader_title"
    android:parentActivityName="MainActivity">
    <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <data android:mimeType="text/plain"/>
    </intent-filter>
</activity>

在我的 FileLoaderActivity 中,我在 onCreate 方法中有以下内容:

// Get the intent that started this activity
Intent intent = getIntent();
Uri data = intent.getData();

//Verify that the type is text file
if (intent.getType().equals("text/plain")) {
    String path = data.getPath();
    File file = new File(path);
    Toast.makeText(getApplicationContext(), path,Toast.LENGTH_SHORT).show();
    if( file.exists())
        Toast.makeText(getApplicationContext(), "I exist",Toast.LENGTH_SHORT).show();
}

现在输出如下:

/my_email@gmail.com/messages/78/attachments/0.1/BEST/false

“我存在”永远不会出现。因此这当然不会打开文件 我已经阅读了很多其他解决方案,但它们似乎是特定于媒体的。 你能帮我得到文件的实际路径吗,

非常感谢您

【问题讨论】:

    标签: android uri text-files absolute-path


    【解决方案1】:

    好的,所以你可以使用

    public String getRealPathFromURI(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        @SuppressWarnings("deprecation")
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
    

    这不仅适用于图像或媒体文件。当然,问题是您必须先下载文件,然后进入您的下载文件夹才能打开它。此外,如果您尝试加载文件,请确保您编辑 Manifest 以获得正确的权限,如下所示:

    <manifest> 
    ...
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    </manifest>
    

    希望这对寻找答案的人有所帮助

    【讨论】:

      猜你喜欢
      • 2011-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多