简体   繁体   中英

Get file name from complex URI

I want to download a file which does not end with file name and extension.

For example below mentioned uri is for downloading a file. What will be the best way to get the name of the file (including its extension) to save it after downloading.

https://pixabay.com/static/uploads/photo/2015/10/01/20/32/mushroom-967719_640.jpg?attachment

The following code is returning "mushroom-967719_640.jpg?attachment"

URL url = new URL(FILE_URI);
...........................
File downloadingFile = new File(url.getFile());
downloadingFile.getName();

I am looking for general solution where I can get the "name.extension" from any kind of such uri.

Writing this from the top of my head:

String filename = downloadingFile.getName().substring(0, downloadingFile.getName().length - 11);

Or to make it more readable

int filenameOriginalLength = downloadingFile.getName().length;
int excessStringLength = 11; // the string "?attachment" is 11 characters long

String filename = downloadingFile.getName().substring(0, filenameOriginalLength - excessStringLength);

Basically what we're doing here is that we're getting the substring of downloadingFile.getName() from the starting letter (index 0) until before the ?attachment appears (length of your string - length of ?attachment).

Might be off by one character, you'd have to fine tune it by running it and adjusting excessStringLength .

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