Search code examples
javapathhierarchy

A step back in a path hierarchy


I have a path to a folder and want to change it. But first I want to get a step back.

String path = "C:\Users\Jurgen\Java\Project\Folder\inner_folder\";

How do I get a step back in a path hierarchy? For example:

String path = "C:\Users\Jurgen\Java\Project\Folder\";

Solution

  • Extract a substring up until the last slash

    String newPath = path.substring(0, path.lastIndexOf('\'));
    

    Edit: (because I'm being challenged on this answer)

    Some people will tell you that treating paths as strings is wrong, in this case it doesn't make a difference. The other option of creating a Path object then using it's .getParent() method or prior to Java 7, a File object.