简体   繁体   中英

How to get file name and extension in android Java

I have an app connected to firebase realtime database. When I am trying to get file path and extension by the following methods, it shows the different name and also show same thing for extension.

Method used to get filename and path:

fileUri = data.getData();
String path = fileUri.getLastPathSegment();
String filename = path.substring(path.lastIndexOf("/")+1);
String extension  = path.substring(path.lastIndexOf(".")+1);


StorageReference filepath = storageReference.child(messagePushID + "." + extension);

filepath.putFile(fileUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task)
    {
        if (task.isSuccessful())
        {

            Map messageDocBody = new HashMap();
            messageDocBody.put("message", task.getResult().toString());
            messageDocBody.put("name",path);
            messageDocBody.put("type",checker);
            messageDocBody.put("extension",extension);
            messageDocBody.put("to",messageReceiverID);
            messageDocBody.put("from",messageSenderID);
            messageDocBody.put("time",time);
            messageDocBody.put("date",date);
            messageDocBody.put("messageID",messagePushID);

数据库

ACTION_GET_CONTENT is documented to give you a Uri with a content scheme. Your code assumes that the Uri has a file scheme and represents a filesystem path.

There is no guaranteed way to get a display name for such a Uri , and there is no requirement that the display name be a filename with a file extension. The content that the user chooses might never have been a file in the first place. You are welcome to try passing the Uri to DocumentFile.fromSingleUri (), then calling getName() on that DocumentFile , to get a display name.

In terms of file extensions, in addition to trying to parse one out of the display name, you could call getType() on the DocumentFile , then use MimeTypeMap to try to get a file extension commonly associated with the MIME type of the content.

Here how I solved the problem, -I thing fileUri.getLastPathSegment() it's returning the content of the file. Get File Name method:

  1. I defined Cursor:

     Cursor cursor = getContentResolver().query(fileUri,null, null, null, null);
  2. nameIndex:

     int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); cursor.moveToFirst(); String filename = cursor.getString(nameIndex);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM