在Java中,你可以使用lastIndexOf方法和substring方法从字符串中截取最后一个斜杠(/)之后的内容。下面是一个示例:

public class Main {  
    public static void main(String[] args) {  
        String str = "path/to/your/file.txt";  
        int lastIndex = str.lastIndexOf("/");  
  
        if (lastIndex != -1) {  
            String contentAfterLastSlash = str.substring(lastIndex + 1);  
            System.out.println(contentAfterLastSlash);  
        } else {  
            System.out.println("No slash found in the string.");  
        }  
    }  
}

在这个例子中,lastIndexOf("/")会返回最后一个斜杠在字符串中的索引。如果字符串中没有斜杠,lastIndexOf会返回-1。然后,我们使用substring(lastIndex + 1)来获取最后一个斜杠之后的所有内容。

如果你处理的是Windows路径,斜杠可能会是反斜杠(\),那么你需要稍作修改,如下所示:

public class Main {  
    public static void main(String[] args) {  
        String str = "path\\to\\your\\file.txt";  
        int lastIndex = str.lastIndexOf("\\");  
  
        if (lastIndex != -1) {  
            String contentAfterLastSlash = str.substring(lastIndex + 1);  
            System.out.println(contentAfterLastSlash);  
        } else {  
            System.out.println("No backslash found in the string.");  
        }  
    }  
}

如果你不确定路径分隔符是什么,可以使用File.separator来获取系统默认的文件分隔符,如下所示:

import java.io.File;  
  
public class Main {  
    public static void main(String[] args) {  
        String str = "path/to/your/file.txt";  
        char separator = File.separatorChar;  
        int lastIndex = str.lastIndexOf(separator);  
  
        if (lastIndex != -1) {  
            String contentAfterLastSlash = str.substring(lastIndex + 1);  
            System.out.println(contentAfterLastSlash);  
        } else {  
            System.out.println("No separator found in the string.");  
        }  
    }  
}

在这个例子中,File.separatorChar会返回系统默认的文件分隔符,这可以是斜杠(/)或反斜杠(\),取决于你的操作系统。

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐