gpt4 book ai didi

android - 如何从 onActivityResult 获取任何文件路径、名称、扩展名?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:23:57 25 4
gpt4 key购买 nike

我的代码是:

1.

File file = new File(Environment.getExternalStorageDirectory(),"myFolder");

Log.d("path", file.toString());

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setDataAndType(Uri.fromFile(file), "*/*");
startActivityForResult(intent,0);

2.

 @Override
protected void onActivityResult(int requestCode,
int resultCode, Intent FileReturnedIntent) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, FileReturnedIntent);

如何获取文件路径、名称、扩展名? (假设文件是​​doc,pdf,csv格式)

最佳答案

它返回文件扩展名,如 pdf、doc .. 等

 public static String getMimeType(Context context, Uri uri) {
String extension;

if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
final MimeTypeMap mime = MimeTypeMap.getSingleton();
extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uri));
} else {
extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());

}

return extension;
}

它返回您获取文件名的真实路径。一位 friend 用过这种方法,非常有用。

Get filename and path from URI from mediastore

public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}

你从这里得到文件名

public String getFileName(Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
if (result == null) {
result = uri.getPath();
int cut = result.lastIndexOf('/');
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}

关于android - 如何从 onActivityResult 获取任何文件路径、名称、扩展名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28824268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com