5

如果我在一个类中有一个字符串变量

MainActivity.selectedFilePath

有这样的价值

/sdcard/images/mr.32.png

我想在某个地方只打印到该文件夹​​的路径而没有文件名

/sdcard/images/
4

12 回答 12

14

你可以做:

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

看见

于 2012-04-19T12:46:42.143 回答
6
    String string = "/sdcard/images/mr.32.png";
    int lastSlash = string.lastIndexOf("/");
    String result = string.substring(0, lastSlash);
    System.out.println(result);
于 2012-04-19T12:46:55.847 回答
2

新文件(MainActivity.selectedFilePath).getParent().getAbsolutePath()

于 2012-04-19T12:45:45.553 回答
2

使用该路径创建一个 File 对象,然后使用File Class中的 getPath 方法。

于 2012-04-19T12:45:54.120 回答
2
String realPath = "/sdcard/images/mr.32.png";
String myPath = realPath.substring(0, realPath.lastIndexOf("/") + 1);
于 2012-04-19T12:46:43.180 回答
2
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);
于 2013-08-29T08:17:12.257 回答
1

您可以使用String.lastIndexOf(int ch);which 为您提供字符 ch 的最后出现

于 2012-04-19T12:46:06.707 回答
1

试试这个 :

File file = new File("path");

parentPath = file.getParent();

parentDir = file.getParentFile();

于 2012-04-19T12:48:45.537 回答
1
  • 文件

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

于 2012-04-19T12:51:30.533 回答
0

查看Apache Commons IO 库中的Apache FileNameUtils ,尤其是getFullPath()

于 2012-04-19T12:46:45.067 回答
0

这是解决方案 -

 String selectedFilePath= "/sdcard/images/mr.32.png";
 selectedFilePath=selectedFilePath.substring(0,selectedFilePath.lastIndexOf("/"));
System.out.println(selectedFilePath);
于 2012-04-19T12:49:01.277 回答
0

Java 11:

String folderOnly = Path.of(MainActivity.selectedFilePath).getParent().toString();
于 2020-01-15T14:34:40.290 回答