我需要解析文件路径以获取其中的文件名。令我困惑的是,Windows 使用 \
作为分隔符,而 Linux 则使用 /
,有时提供的文件路径甚至可以同时包含两种分隔符。
当然,我可以这样做:
int slash = filePath.lastIndexOf("/");
int backslash = filePath.lastIndexOf("\\");
fileName = filePath.substring(slash > backslash ? slash : backslash);
如果我有更多的分隔符,是否有更好的方法?(对于文件路径可能没有更好的方法)
File f = new File(fileName); String name = f.getName();
可翻译为:创建一个文件对象f
,其路径名为fileName
,然后获取该文件对象的名称并将其赋值给字符串变量name
。 - Andrew Thompson