java 如何从文件 URI 中提取文件名并为其创建链接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/482589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to extract the file name from a file URI and create a link for the same?
提问by Jagmal
My problem is ::
我的问题是::
From a string like "/usr/folder1/folder2/filename.ext"
来自像“/usr/folder1/folder2/filename.ext”这样的字符串
- I have to extract out file name only for display (filename.ext only).
- My question would be how should I do it? Splitting on "/" and taking the last element is one way but doesn't smell nice to me.
- I have to create a hyperlink which uses URI of the file as the destination. That will be something similar to file://domain.com/usr/folder1/folder2/filename.ext
- 我必须提取文件名仅用于显示(仅限文件名.ext)。
- 我的问题是我应该怎么做?拆分“/”并取最后一个元素是一种方式,但对我来说并不好闻。
- 我必须创建一个使用文件 URI 作为目标的超链接。这将类似于 file://domain.com/usr/folder1/folder2/filename.ext
I looked at URI and URL interfaces in java.net but could not find anything useful there.
我查看了 java.net 中的 URI 和 URL 接口,但在那里找不到任何有用的东西。
Also, in some cases, my file path can have COMMA, SPACE etc (Windows folders). So, keep that in mind when giving any ideas.
此外,在某些情况下,我的文件路径可以包含逗号、空格等(Windows 文件夹)。因此,在提出任何想法时请记住这一点。
回答by trilobite
You could try something like this:
你可以尝试这样的事情:
File file = new File("/usr/folder1/folder2/filename.ext");
System.out.println(file.getName());
I wasn't sure whether this would work if the file does not exist, but have just tried it and it appears to work OK.
如果文件不存在,我不确定这是否可行,但刚刚尝试过,它似乎可以正常工作。
回答by schnatterer
CommonsIOprovides solutions for this problem: FilenameUtils.getName(), returns the file name + extension.
CommonsIO针对这个问题提供了解决方案:FilenameUtils.getName(), 返回文件名+扩展名。
String filename = FilenameUtils.getName("/usr/folder1/folder2/filename.ext");
System.out.println(filename); // Returns "filename.ext"
回答by Nicolas
You should have a look to the File class. Especially to the getName()method.

