从 Java 中的文件位置获取文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1011287/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:15:41  来源:igfitidea点击:

Get file name from a file location in Java

javaurlstringpathfilenames

提问by Ankur

I have a Stringthat 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?

我有一个String提供文件的绝对路径(包括文件名)。我只想获取文件名。什么是最简单的方法来做到这一点?

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.

它需要尽可能通用,因为我无法提前知道 URL 是什么。我不能简单地创建一个 URL 对象并使用getFile()- 尽管如果可能的话这一切都是理想的 - 因为它不一定是http://前缀,它可以是 c:/ 或类似的东西。

采纳答案by akarnokd

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.

请注意,第一个解决方案取决于系统。它只考虑系统的路径分隔符。因此,如果您的代码在 Unix 系统上运行并收到 Windows 路径,它将无法工作。处理 Internet Explorer 发送的文件上传时就是这种情况。

回答by victor hugo

new File(absolutePath).getName();

回答by skaffman

Apache Commons IOprovides 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.

Apache Commons IO提供了 FilenameUtils 类,它为您提供了一组非常丰富的实用函数,用于轻松获取文件名的各种组件,尽管 java.io.File 类提供了基础知识。

回答by Sebastian Juarez

From Apache Commons IO FileNameUtils

来自Apache Commons IO FileNameUtils

String fileName = FilenameUtils.getName(stringNameWithPath);

回答by Om Sao

Here are 2 ways(both are OS independent.)

这里有 2 种方式(两者都是独立于操作系统的。)

Using Paths: Since 1.7

使用Paths:自 1.7

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

Using FilenameUtilsin Apache Commons IO :

使用FilenameUtils了Apache下议院IO:

String name1 = FilenameUtils.getName("/ab/cd/xyz.txt");
String name2 = FilenameUtils.getName("c:\ab\cd\xyz.txt");