Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split filesystem path in Java?

Tags:

java

string

path

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/
like image 266
Jeegar Patel Avatar asked Apr 19 '12 12:04

Jeegar Patel


People also ask

How to split a path in Java?

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 "".

What does split \\ do in Java?

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.

What is the file separator in Java?

File. separator: Platform dependent default name-separator character as String. For windows, it's '\' and for unix it's '/'. File.

How do you split a line in Java?

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?\\


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

See it

like image 200
codaddict Avatar answered Oct 22 '22 00:10

codaddict


    String string = "/sdcard/images/mr.32.png";
    int lastSlash = string.lastIndexOf("/");
    String result = string.substring(0, lastSlash);
    System.out.println(result);
like image 25
Kai Avatar answered Oct 21 '22 23:10

Kai