如果我在一个类中有一个字符串变量
MainActivity.selectedFilePath
有这样的价值
/sdcard/images/mr.32.png
我想在某个地方只打印到该文件夹的路径而没有文件名
/sdcard/images/
你可以做:
File theFile = new File("/sdcard/images/mr.32.png");
String parent = theFile.getParent();
或(不推荐)
String path = "/sdcard/images/mr.32.png";
String parent = path.replaceAll("^(.*)/.*?$","$1");
String string = "/sdcard/images/mr.32.png";
int lastSlash = string.lastIndexOf("/");
String result = string.substring(0, lastSlash);
System.out.println(result);
新文件(MainActivity.selectedFilePath).getParent().getAbsolutePath()
使用该路径创建一个 File 对象,然后使用File Class中的 getPath 方法。
String realPath = "/sdcard/images/mr.32.png";
String myPath = realPath.substring(0, realPath.lastIndexOf("/") + 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);
您可以使用String.lastIndexOf(int ch);
which 为您提供字符 ch 的最后出现
试试这个 :
File file = new File("path");
parentPath = file.getParent();
parentDir = file.getParentFile();
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 "".
查看Apache Commons IO 库中的Apache FileNameUtils ,尤其是getFullPath()。
这是解决方案 -
String selectedFilePath= "/sdcard/images/mr.32.png";
selectedFilePath=selectedFilePath.substring(0,selectedFilePath.lastIndexOf("/"));
System.out.println(selectedFilePath);
Java 11:
String folderOnly = Path.of(MainActivity.selectedFilePath).getParent().toString();