android 获取路径
时间: 2023-10-18 15:10:09 浏览: 87
在 Android 开发中,获取文件路径的方法有很多种。其中,常用的方法有以下几种:
1. 通过 Uri 获取路径
```java
public String getRealPathFromUri(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String filePath = cursor.getString(column_index);
cursor.close();
return filePath;
}
```
2. 通过 FileProvider 获取路径
```java
public static Uri getUriFromFile(Context context, File file) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);
} else {
return Uri.fromFile(file);
}
}
public String getRealPathFromUri(Uri uri) {
String filePath = "";
if (DocumentsContract.isDocumentUri(this, uri)) {
String documentId = DocumentsContract.getDocumentId(uri);
if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
String id = documentId.split(":")[1];
String selection = MediaStore.Images.Media._ID + "=" + id;
filePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
filePath = getImagePath(contentUri, null);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
filePath = getImagePath(uri, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
filePath = uri.getPath();
}
return filePath;
}
public String getImagePath(Uri uri, String selection) {
String path = null;
Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
}
return path;
}
```
3. 直接获取文件路径
```java
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test.txt");
String filePath = file.getAbsolutePath();
```
阅读全文