Reputation: 27210
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
Reputation: 1364
Java 11:
String folderOnly = Path.of(MainActivity.selectedFilePath).getParent().toString();
Upvotes: 0
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
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");
Upvotes: 15
Reputation: 939
If the Files actually exist on the box, you could wrap the Strings up in a File object and call File.getParent().
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.
You could use regular expressions to replace the part after the last / with "".
Upvotes: 1
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
Reputation: 29
try this :
File file = new File("path");
parentPath = file.getParent();
parentDir = file.getParentFile();
Upvotes: 1
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
Reputation: 272297
Check out Apache FileNameUtils in the Apache Commons IO library, and in particular getFullPath().
Upvotes: 0
Reputation: 3764
String realPath = "/sdcard/images/mr.32.png";
String myPath = realPath.substring(0, realPath.lastIndexOf("/") + 1);
Upvotes: 2
Reputation: 1480
You can use String.lastIndexOf(int ch);
which gives you the last occurrense of the character ch
Upvotes: 1
Reputation: 4228
Create a File object with that path and then use getPath method from File Class.
Upvotes: 2
Reputation: 15699
new File(MainActivity.selectedFilePath).getParent().getAbsolutePath()
Upvotes: 2