How to split file system path in Java?

If I have a string variable inside one class

MainActivity.selectedFilePath

which matters

/sdcard/images/mr.32.png

and I want to print somewhere only the path to this folder without a file name

/sdcard/images/
+3
source share
11 answers

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");

Take a look

+12
source
    String string = "/sdcard/images/mr.32.png";
    int lastSlash = string.lastIndexOf("/");
    String result = string.substring(0, lastSlash);
    System.out.println(result);
+6
source

(MainActivity.selectedFilePath).getParent(). getAbsolutePath()

+2

File , getPath File Class.

+2
String realPath = "/sdcard/images/mr.32.png";
String myPath = realPath.substring(0, realPath.lastIndexOf("/") + 1);
+2

String.lastIndexOf(int ch);, ch

+1

:

File file = new File("path");

parentPath = file.getParent();

parentDir = file.getParentFile();

+1

, File File.getParent().

  • String.split()

, String.split(), String "/" . . .

/ "".

+1
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);
+1

Apache FileNameUtils IO Apache Commons , , getFullPath().

0

-

 String selectedFilePath= "/sdcard/images/mr.32.png";
 selectedFilePath=selectedFilePath.substring(0,selectedFilePath.lastIndexOf("/"));
System.out.println(selectedFilePath);
0

All Articles