Android: Get file name and extension of any file

后端 未结 1 872
猫巷女王i
猫巷女王i 2021-01-17 08:32

The issue I have, is that i can\'t extract the file exetension from files choosen on a smartphone with Android 9. The problem doesn\'t appear on devices with Android 8 or le

1条回答
  •  借酒劲吻你
    2021-01-17 09:06

    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);
    }
    

    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.

    0 讨论(0)
提交回复
热议问题