我有一个屏幕,点击按钮打开一个文件选择器,然后我选择一个名为“Test.jpg”的文件进行进一步操作。 我使用以下代码获取该文件的名称。
Uri uri = data.getData();
File file = new File(uri.getPath());
String fileName = file.getName();
这是调试器的结果
file.getName() => 167522
file.toString() => /external/images/media/167522
我想获取 Test.jpg 作为我的文件名。 请让我知道我的代码有什么问题。
最佳答案
需要来自您的 uri 的路径。这是从 uri 获取路径的方法。
public String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
获取文件名
try{
//call the getPath uri with context and uri
//To get path from uri
String path = getPath(this, uri);
File file = new File(path);
String filename = file.getName();
Log.e(TAG, "File Name: " + filename);
}catch(Exception e){
e("Err", e.toString()+"");
}
输出
uri: content://com.android.providers.media.documents/document/image%3A12876
FileName : profile.png
关于java - Android:所选文件的文件名不正确(来自文件选择器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45054005/