Android 中选择本地文件并获取文件路径

发布于:2024-11-03 ⋅ 阅读:(7) ⋅ 点赞:(0)

1. 使用Intent.ACTION_GET_CONTENT(适用于较简单的文件选择场景)

步骤一:在Activity中启动文件选择器

private static final int FILE_SELECT_CODE = 1;

private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*"); // 设置为选择所有类型文件,可根据需要修改,如 "application/pdf" 表示只选择 PDF 文件
    startActivityForResult(intent, FILE_SELECT_CODE);
}

步骤二:在onActivityResult中获取文件Uri并尝试转换为路径

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == FILE_SELECT_CODE && resultCode == RESULT_OK) {
        Uri uri = data.getData();
        String filePath = getPathFromUri(uri);
        Log.d("File Path", filePath);
        // 可以在这里对获取到的文件路径进行后续操作,如读取文件内容等
    }
}

步骤三:实现getPathFromUri方法来处理不同类型的Uri获取路径

public String getPathFromUri(Uri uri) {
    String path = null;
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        if (cursor!= null) {
            if (cursor.moveToFirst()) {
                int index = cursor.getColumnIndex("_data");
                if (index > -1) {
                    path = cursor.getString(index);
                }
            }
            cursor.close();
        }
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        path = uri.getPath();
    }
    return path;
}

2. 使用Storage Access Framework(更通用且安全,特别是对于 Android 4.4 及以上版本)

步骤一:启动文件选择器

private static final int REQUEST_CODE_OPEN_DOCUMENT = 1;

private void openDocument() {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("*/*");
    startActivityForResult(intent, REQUEST_CODE_OPEN_DOCUMENT);
}

步骤二:在onActivityResult中处理选择结果并获取路径

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_CODE_OPEN_DOCUMENT && resultCode == RESULT_OK) {
        Uri uri = data.getData();
        String filePath = getPathFromSAFUri(uri);
        Log.d("File Path", filePath);
    }
}

步骤三:实现getPathFromSAFUri方法来处理SAF相关的Uri获取路径

public String getPathFromSAFUri(Uri uri) {
    if (DocumentsContract.isDocumentUri(this, uri)) {
        if (isExternalStorageDocument(uri)) {
            String docId = DocumentsContract.getDocumentId(uri);
            String[] split = docId.split(":");
            if ("primary".equals(split[0])) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }
        } else if (isDownloadsDocument(uri)) {
            String id = DocumentsContract.getDocumentId(uri);
            Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
            return getDataColumn(this, contentUri, null, null);
        } else if (isMediaDocument(uri)) {
            String docId = DocumentsContract.getDocumentId(uri);
            String[] split = docId.split(":");
            String type = split[0];
            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }
            String selection = "_id=?";
            String[] selectionArgs = new String[]{split[1]};
            return getDataColumn(this, contentUri, selection, selectionArgs);
        }
    } else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(this, uri, null, null);
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }
    return null;
}

private boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

private boolean isDownloadsDocument(uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

private boolean isMediaDocument(uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

public String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {column};
    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
        if (cursor!= null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(columnIndex);
        }
    } finally {
        if (cursor!= null)
            cursor.close();
    }
    return null;
}

至此就完成了在Android中选择文件并获取路径的方法,可以根据自己的需求进行调整