且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取Android中任何文件的文件名和扩展名

更新时间:2021-12-13 07:55:43

对于该解决方案,我正在使用MediaStore提取所选文件的名称和扩展名.因此,我将onActivityResult中的代码替换为以下代码:

For the solution I am using the MediaStore to extract the name and extension of a choosen file. So I replace code in onActivityResult with following code:

String path = new File(data.getData().getPath()).getAbsolutePath();

if(path != null){
  uri = data.getData();

  String filename;
  Cursor cursor = getContentResolver().query(uri,null,null,null,null);

  if(cursor == null) filename=uri.getPath();
  else{
    cursor.moveToFirst();
    int idx = cursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME);
    filename = cursor.getString(idx);
    cursor.close();
  }

  name = filename.substring(filename.lastIndexOf("."));
  extension = filename.substring(filename.lastIndexOf(".")+1);
}

因此,使用MediaStore.File.FileColumns.DISPLAY_NAME可以从使用文件选择器选择的任何文件中获取文件名和扩展名.

So with MediaStore.File.FileColumns.DISPLAY_NAME it's possible to get the file name and extension from any file choosen with a file chooser.