Java中获取文件名的方法有哪些?哪种最简单高效?
- 后端开发
- 2025-09-16
- 4
在Java中,获取文件名可以通过多种方式实现,以下是一些常见的方法:
使用File类
Java的File类提供了获取文件名的方法,以下是如何使用File类获取文件名的示例:
import java.io.File; public class Main { public static void main(String[] args) { File file = new File("C:\path\to\your\file.txt"); String fileName = file.getName(); System.out.println("File Name: " + fileName); } }
使用Path类
Java 7 引入了java.nio.file.Paths和java.nio.file.Path类,这些类提供了更高级的文件操作功能,以下是如何使用Path类获取文件名的示例:

使用URL类
如果你有一个文件的URL,你可以使用URL类来获取文件名:
import java.net.URL; public class Main { public static void main(String[] args) { try { URL url = new URL("file:C:\path\to\your\file.txt"); String fileName = url.getPath(); System.out.println("File Name: " + fileName); } catch (Exception e) { e.printStackTrace(); } } }
使用URI类
如果你有一个文件的URI,你可以使用URI类来获取文件名:

使用FilenameUtils类
Apache Commons IO库中的FilenameUtils类提供了很多有用的文件操作方法,包括获取文件名,以下是如何使用FilenameUtils类获取文件名的示例:
import org.apache.commons.io.FilenameUtils; public class Main { public static void main(String[] args) { String fileName = FilenameUtils.getName("C:\path\to\your\file.txt"); System.out.println("File Name: " + fileName); } }
下面是一个表格,归纳了上述方法:
| 方法 | 代码示例 | 说明 |
|---|---|---|
| File类 | String fileName = file.getName(); | 直接使用File类的getName()方法 |
| Path类 | String fileName = path.getFileName().toString(); | 使用Path类的getFileName()方法 |
| URL类 | String fileName = url.getPath(); | 使用URL类的getPath()方法 |
| URI类 | String fileName = uri.getPath(); | 使用URI类的getPath()方法 |
| FilenameUtils类 | String fileName = FilenameUtils.getName("C:\path\to\your\file.txt"); | 使用Apache Commons IO库的FilenameUtils类 |
FAQs
Q1: 如果文件路径包含空格,如何获取文件名?

A1: 无论文件路径中是否包含空格,上述方法都可以正常工作,Java的文件路径处理是透明的,空格会被正确处理。
Q2: 如果我想获取不带扩展名的文件名,怎么办?
A2: 如果你想获取不带扩展名的文件名,可以使用FilenameUtils类中的getBaseName()方法:
import org.apache.commons.io.FilenameUtils; public class Main { public static void main(String[] args) { String fileName = FilenameUtils.getBaseName("C:\path\to\your\file.txt"); System.out.println("File Name without Extension: " + fileName); } }