I have a list of paths and i need to remove the last directory of each path.
Path : "I:\Directory_1\Directory_2\Directory_3-Sometext" I used the split method to remove everyting on the right side of the '-'
I've tried using split() removing one by one and then regrouping everything in one string. I've tried splitting everyting on ("\") and using lenght()
//Removes text after '-'
String [] parts = path.split("-")
String partsA = parts[0]
String [] newParts = partsA.split("\\\\");
String partsB = newParts[newParts.length-1];
partsA = partsA.substring(partsA.length()-partsB.length(),partsA.length()+partsB.length());
I expect the ouput to be
\Directory_1\Directory_2
without the last directory and the text
Instead of using string manipulation, you could use proper path/file objects, with the additional benefit that it can handle other types of paths (for example a unix path such as /home/directory1):
String f = "I:\\Directory_1\\Directory_2\\Directory_3-Sometext";
Path p = Paths.get(f);
Path parent = p.getParent();
System.out.println(parent.toString());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With