简体   繁体   English

如何从文件URI中提取文件名并为其创建链接?

[英]How to extract the file name from a file URI and create a link for the same?

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). 我必须提取文件名仅用于显示(仅限filename.ext)。
    • 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. 我必须创建一个超链接,使用该文件的URI作为目标。 That will be something similar to file://domain.com/usr/folder1/folder2/filename.ext 这将类似于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). 此外,在某些情况下,我的文件路径可以有COMMA,SPACE等(Windows文件夹)。 So, keep that in mind when giving any ideas. 因此,在提出任何想法时请记住这一点。

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. 我不确定如果文件不存在,这是否会起作用,但是刚刚尝试了它,它似乎工作正常。

CommonsIO provides 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"

You should have a look to the File class . 你应该看一下File类 Especially to the getName() method. 特别是对getName()方法。

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

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