我正在使用 Intent 让用户选择一个文件,在用户完成后我想知道所选文件的文件类型。
Intent :
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
在我的 onActivityResult 中,我想通过 intent.getData() 及其所有“子方法”(getScheme()、getLastPathSegment() 等)从 Intent 中提取路径。但是,我只获得所选文件的 Uri。
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
我已经看到了如何在只允许用户选择图像或音频时获取绝对路径的解决方案。但是,如果我想让用户从不同的文件类型中进行选择,我该如何获取绝对路径(具有名称和文件结尾的真实路径,例如 MyPicture.jpeg)?
我一直在努力尝试在 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);
最佳答案
我假设文件结尾是指文件扩展名? (即 mp4)
如果是这样,您可以使用 ContentResolver 获取 mimetype:
String mimeType = getContentResolver().getType(sourceUri);
假设它们在 MediaStore 中,这将为您提供 mimetype,如果您有内容 Uri,它们应该是这样。所以你会得到类似“image/png”、“video/mp4”等的东西。
然后您可以使用 MimeTypeMap 从 mimetype 获取文件扩展名:
String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
请注意,您永远不应该在“/”之后对 mimetype 进行子串以获取扩展名,因为某些 mimetype 不使用其扩展名,例如 mimetype 为“video/quicktime”的“.mov”文件
关于android - ACTION_GET_CONTENT : How to get file-ending when searching for multiple file types?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16148686/