简体   繁体   English

从复杂的URI获取文件名

[英]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. 例如,下面提到的uri用于下载文件。 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 https://pixabay.com/static/uploads/photo/2015/10/01/20/32/mushroom-967719_640.jpg?附件

The following code is returning "mushroom-967719_640.jpg?attachment" 以下代码返回“ 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. 我正在寻找可以从任何此类uri获取“ name.extension”的常规解决方案。

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). 基本上,我们在这里所做的是从开始字母(索引为0)开始获取downloadingFile.getName()的子字符串,直到出现?attachment为止(您的字符串长度-附件长度)。

Might be off by one character, you'd have to fine tune it by running it and adjusting excessStringLength . 可能excessStringLength一个字符,您必须通过运行它并调整excessStringLength

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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