Jeegar Patel
Jeegar Patel

Reputation: 27210

How to split filesystem path in Java?

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/

Upvotes: 6

Views: 23578

Answers (12)

yoni
yoni

Reputation: 1364

Java 11:

String folderOnly = Path.of(MainActivity.selectedFilePath).getParent().toString();

Upvotes: 0

sathya
sathya

Reputation: 25

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

Upvotes: 2

codaddict
codaddict

Reputation: 455042

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

Upvotes: 15

Qkyrie
Qkyrie

Reputation: 939

  • Files

If the Files actually exist on the box, you could wrap the Strings up in a File object and call File.getParent().

  • String.split()

If the files don't exist, you could use the String.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.

  • Regular expressions

You could use regular expressions to replace the part after the last / with "".

Upvotes: 1

kundan bora
kundan bora

Reputation: 3889

Here is the solution -

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

Upvotes: 0

try this :

File file = new File("path");

parentPath = file.getParent();

parentDir = file.getParentFile();

Upvotes: 1

Kai
Kai

Reputation: 39641

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

Upvotes: 6

Brian Agnew
Brian Agnew

Reputation: 272297

Check out Apache FileNameUtils in the Apache Commons IO library, and in particular getFullPath().

Upvotes: 0

Dani
Dani

Reputation: 3764

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

Upvotes: 2

DGomez
DGomez

Reputation: 1480

You can use String.lastIndexOf(int ch); which gives you the last occurrense of the character ch

Upvotes: 1

Averroes
Averroes

Reputation: 4228

Create a File object with that path and then use getPath method from File Class.

Upvotes: 2

npe
npe

Reputation: 15699

new File(MainActivity.selectedFilePath).getParent().getAbsolutePath()

Upvotes: 2

Related Questions