How to split filesystem path in Java?
Solution 1
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");
Solution 2
String string = "/sdcard/images/mr.32.png";
int lastSlash = string.lastIndexOf("/");
String result = string.substring(0, lastSlash);
System.out.println(result);
Solution 3
Create a File object with that path and then use getPath method from File Class.
Solution 4
String realPath = "/sdcard/images/mr.32.png";
String myPath = realPath.substring(0, realPath.lastIndexOf("/") + 1);
Solution 5
final String dir = System.getProperty("user.dir");
String[] array = dir.split("[\\\\/]",-1) ;
String arrval="";
for (int i=0 ;i<array.length;i++)
{
arrval=arrval+array[i];
}
System.out.println(arrval);
Jeegar Patel
Written first piece of code at Age 14 in HTML & pascal Written first piece of code in c programming language at Age 18 in 2007 Professional Embedded Software engineer (Multimedia) since 2011 Worked in Gstreamer, Yocto, OpenMAX OMX-IL, H264, H265 video codec internal, ALSA framework, MKV container format internals, FFMPEG, Linux device driver development, Android porting, Android native app development (JNI interface) Linux application layer programming, Firmware development on various RTOS system like(TI's SYS/BIOS, Qualcomm Hexagon DSP, Custom RTOS on custom microprocessors)
Updated on June 14, 2022Comments
-
Jeegar Patel almost 2 years
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/
-
Steven over 11 yearsThe file does not need to exist on the file system to call getParent().
-
Nicholas DiPiazza about 8 yearsfinally the regexp i was looking for