java中从含反斜杠路径截取文件名的方法

例如:获取到的文件路径为C:Documents and SettingsLeeoMy Documentslogo.gif
现在想要取得图片的名称logo.gif,我们知道反斜杠“”是转义字符,所以不能直接
String temp[] = filePath.split("");//filePath的值就是上面的文件路径

来分割文件路径,而应该这样写
/*
*java中\表示一个,而regex中\也表示,
*所以当\\解析成regex的时候为\
**/
String temp[] = filePath.split("\\");

在Linux系统中
System.getProperty("file.separator", "\")输出为“/”,

而在Windows系统中输出为“”,所以要兼容两者可以这么写
String temp[] = filePath.replaceAll("\\","/").split("/");

获取文件名称的完整代码如下:
String temp[] = filePath.replaceAll("\\","/").split("/");
String fileName = ""
if(temp.length > 1){
    fileName = temp[temp.length - 1];
}

原文地址:https://www.cnblogs.com/xunbu7/p/4822773.html