在 Android 中通过 Intent 选择文件后如何查找所选文件的类型?
How to find the type of a selected file after Picking the file via an Intent in Android?
我可以通过以下代码选择PDF或图片文件:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
String[] mimetypes = {"image/*", "application/pdf"
};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
startActivityForResult(Intent.createChooser(intent, "Select a file"),REQUEST_GET_SINGLE_FILE);
我通过以下方法收到结果:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_GET_SINGLE_FILE ) {
Uri selectedImageUri = data.getData();
....
....
我需要查找所选文件是PDF还是图片?如何找到文件类型?
我建议您阅读 ContentResolver documentation
and then read this Retriefe-info documentation
然后您将能够获得文件的扩展名。
MIME 类型
Uri selectedImageUri = data.getData();
String mimeType = getContentResolver().getType(selectedImageUri);
它会 return 像这样:
"image/jpeg"
"image/png"
如果你想使用 Cursor
你可以这样做:
Cursor cursor = getContentResolver().query(selectedImageUri, null, null, null, null);
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(0);
String filePath = cursor.getString(columnIndex);
String extension = filePath.substring(filePath.lastIndexOf(".") + 1); //will return pdf
}
cursor.close();
我可以通过以下代码选择PDF或图片文件:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
String[] mimetypes = {"image/*", "application/pdf"
};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
startActivityForResult(Intent.createChooser(intent, "Select a file"),REQUEST_GET_SINGLE_FILE);
我通过以下方法收到结果:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_GET_SINGLE_FILE ) {
Uri selectedImageUri = data.getData();
....
....
我需要查找所选文件是PDF还是图片?如何找到文件类型?
我建议您阅读 ContentResolver documentation
and then read this Retriefe-info documentation
然后您将能够获得文件的扩展名。
MIME 类型
Uri selectedImageUri = data.getData();
String mimeType = getContentResolver().getType(selectedImageUri);
它会 return 像这样:
"image/jpeg"
"image/png"
如果你想使用 Cursor
你可以这样做:
Cursor cursor = getContentResolver().query(selectedImageUri, null, null, null, null);
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(0);
String filePath = cursor.getString(columnIndex);
String extension = filePath.substring(filePath.lastIndexOf(".") + 1); //will return pdf
}
cursor.close();