Get file name from a file location in Java

2019-01-23 11:13发布

I have a String that provides an absolute path to a file (including the file name). I want to get just the file's name. What is the easiest way to do this?

It needs to be as general as possible as I cannot know in advance what the URL will be. I can't simply create a URL object and use getFile() - all though that would have been ideal if it was possible - as it's not necessarily an http:// prefix it could be c:/ or something similar.

5条回答
男人必须洒脱
2楼-- · 2019-01-23 11:21

Apache Commons IO provides the FilenameUtils class which gives you a pretty rich set of utility functions for easily obtaining the various components of filenames, although The java.io.File class provides the basics.

查看更多
▲ chillily
3楼-- · 2019-01-23 11:22

From Apache Commons IO FileNameUtils

String fileName = FilenameUtils.getName(stringNameWithPath);
查看更多
你好瞎i
4楼-- · 2019-01-23 11:31

Here are 2 ways(both are OS independent.)

Using Paths : Since 1.7

Path p = Paths.get(<Absolute Path of Linux/Windows system>);
String fileName = p.getFileName().toString();
String directory = p.getParent().toString();

Using FilenameUtils in Apache Commons IO :

String name1 = FilenameUtils.getName("/ab/cd/xyz.txt");
String name2 = FilenameUtils.getName("c:\\ab\\cd\\xyz.txt");
查看更多
太酷不给撩
5楼-- · 2019-01-23 11:34
new File(absolutePath).getName();
查看更多
霸刀☆藐视天下
6楼-- · 2019-01-23 11:41
new File(fileName).getName();

or

int idx = fileName.replaceAll("\\\\", "/").lastIndexOf("/");
return idx >= 0 ? fileName.substring(idx + 1) : fileName;

Notice that the first solution is system dependent. It only takes the system's path separator character into account. So if your code runs on a Unix system and receives a Windows path, it won't work. This is the case when processing file uploads being sent by Internet Explorer.

查看更多
登录 后发表回答