从 Java 中的文件位置获取文件名 [英] Get file name from a file location in Java
问题描述
我有一个 String
提供文件的绝对路径(包括文件名).我只想获取文件名.最简单的方法是什么?
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?
它需要尽可能通用,因为我无法提前知道 URL 是什么.我不能简单地创建一个 URL 对象并使用 getFile()
- 尽管如果可能的话这一切都是理想的 - 因为它不一定是 http://
前缀可以是 c:/或类似的东西.
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.
推荐答案
new File(fileName).getName();
或
int idx = fileName.replaceAll("\\", "/").lastIndexOf("/");
return idx >= 0 ? fileName.substring(idx + 1) : fileName;
请注意,第一个解决方案取决于系统.它只考虑系统的路径分隔符.因此,如果您的代码在 Unix 系统上运行并收到 Windows 路径,它将无法工作.处理 Internet Explorer 发送的文件上传时就是这种情况.
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.
这篇关于从 Java 中的文件位置获取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!