Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use split() to remove last destination in path?

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

like image 512
Francisco Lopes Avatar asked Oct 29 '25 05:10

Francisco Lopes


1 Answers

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());
like image 162
assylias Avatar answered Oct 31 '25 20:10

assylias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!