-1

I have a String file path

String filePath = "/tmp/test/save/data/java/"

and would like to remove the last 2 directories and last / so that,

String filePath = "/tmp/test/save"

I don't want to create a substring removing the last 10 characters, as the directories might change in length.
I was thinking about doing a combination of split (setting a limit and removing the final index), then join to recreate the string with / seperators, but wondering if there's a cleaner way ?

guy_sensei
  • 513
  • 1
  • 6
  • 21

3 Answers3

5

You could use java.nio.file.Path#getParent.

String result = Paths.get("/tmp/test/save/data/java/").getParent()
                  .getParent().toString();
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
2

From java.nio.file.Path we can use subpath:

Path path = Paths.get("/tmp/test/save/data/java/");
String result = p.subpath(0, p.getNameCount() - 2);
Ervin Szilagyi
  • 14,274
  • 2
  • 25
  • 40
-1

You can use a combination of lastIndexOf("/") and subString() in a for loop to remove the unwanted directories. Java String documentations to learn how to use the methods.

kiszkot
  • 19
  • 2