且构网

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

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

更新时间:2022-01-21 08:10:26

对于该解决方案,我正在使用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();
  }

  String name = filename.substring(0,filename.lastIndexOf("."));
  String 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.