在 Android 中,使用 FileChooser 可以让用户从设备中选择文件
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
private static final int FILE_PICK_REQUEST_CODE = 1;
private void openFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
try {
startActivityForResult(
Intent.createChooser(intent, "选择文件"),
FILE_PICK_REQUEST_CODE);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "请安装文件管理器", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILE_PICK_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
Uri uri = data.getData();
if (uri != null) {
// 在这里处理所选文件的 Uri,例如获取文件名和读取内容等
String fileName = getFileNameFromUri(this, uri);
// ...
}
}
}
public String getFileNameFromUri(Context context, Uri uri) {
String fileName = "";
if (uri.getScheme().equalsIgnoreCase("content")) {
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
fileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
if (fileName.isEmpty()) {
fileName = uri.getPath();
int cut = fileName.lastIndexOf('/');
if (cut != -1) {
fileName = fileName.substring(cut + 1);
}
}
return fileName;
}
openFileChooser()
方法即可。注意:在 Android 10 及更高版本中,外部存储机制发生了变化。为了访问外部存储,需要在运行时请求分区存储权限。具体信息可参考 官方文档。