If I have a string variable inside one class
MainActivity.selectedFilePath
which has a value like this
/sdcard/images/mr.32.png
and I want to print somewhere only the path up to that folder without the filename
/sdcard/images/
split() function to split the String with "/" as delimiter. You could then drop the last String in the array and rebuild it. This approach is rather dirty though. You could use regular expressions to replace the part after the last / with "".
split() The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings.
File. separator: Platform dependent default name-separator character as String. For windows, it's '\' and for unix it's '/'. File.
Java 8 provides an “\R” pattern that matches any Unicode line-break sequence and covers all the newline characters for different operating systems. Therefore, we can use the “\R” pattern instead of “\\r?\\
You can do:
File theFile = new File("/sdcard/images/mr.32.png");
String parent = theFile.getParent();
Or (less recommended)
String path = "/sdcard/images/mr.32.png";
String parent = path.replaceAll("^(.*)/.*?$","$1");
See it
String string = "/sdcard/images/mr.32.png";
int lastSlash = string.lastIndexOf("/");
String result = string.substring(0, lastSlash);
System.out.println(result);
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