6

I am using an Intent to let the user select a file, and after the user has done that I want to know what kind of file-type the selected file is.

The intent:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");

In my onActivityResult I want to extract the path from the intent through intent.getData() and all of it's "submethods" (getScheme(), getLastPathSegment() etc). However, I only get the Uri for the selected file.

Example of Uris':

Uri: content://media/external/audio/media/15185 //This is an audiofile
Uri: content://media/external/audio/media/20 //Another audiofile
Uri: content://media/external/images/media/20577 //this is a picture
Uri: file:///storage/emulated/0/testWed%20Apr%2017%2011%3A10%3A34%20CEST%202013 //This is a file

I've seen solutions of how to get the absolute path when the user is only allowed to chose images or audios. But how do I do I get the absolutePath (the real path with the name and file-ending, e.g. MyPicture.jpeg) if I want to allow the user to select from different file types?

The code I've been twiggling with to try to get the path-name in onActivityResult(int requestCode, int resultCode

         String fileName = data.getData().getLastPathSegment().toString();
         System.out.println("Uri: " +data.getData().toString());
         File f = new File(fileName);
         System.out.println("TrYinG wIWThA Da FiLE: " +f.getAbsolutePath());
         System.out.println("FileNAME!!!: "+fileName);
4

1 回答 1

4

通过文件结尾,我假设您的意思是文件扩展名?(即mp4)

如果是这样,您可以使用ContentResolver获取 mimetype:

String mimeType = getContentResolver().getType(sourceUri);

如果您有内容,这将为您提供 mimetype 假设它们在MediaStore它们应该包含的范围内Uri。所以你会得到类似“image/png”、“video/mp4”等的东西。

然后您可以使用MimeTypeMap从 mimetype 获取文件扩展名:

String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);

请注意,您永远不应该在“/”之后对 mimetype 进行子串化以获取扩展名,因为某些 mimetype 不使用其扩展名,例如具有 mimetype“video/quicktime”的“.mov”文件

于 2013-10-11T20:26:32.050 回答