簡體   English   中英

如何在Java中拆分文件系統路徑?

[英]How to split filesystem path in Java?

如果我在一個類中有一個字符串變量

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); 這為您提供了字符 ch 的最后一次出現

試試這個 :

File file = new File("path");

parentPath = file.getParent();

parentDir = file.getParentFile();

  • 文件

如果文件實際上存在於盒子上,您可以將字符串包裝在一個 File 對象中並調用File.getParent()

  • 字符串.split()

如果文件不存在,您可以使用 String.split() 函數將字符串拆分為“/”作為分隔符。 然后您可以刪除數組中的最后一個字符串並重建它。 雖然這種方法相當骯臟。

  • 常用表達

您可以使用正則表達式將最后一個 / 之后的部分替換為“”。

查看 Apache Commons IO 庫中的Apache FileNameUtils ,特別是getFullPath()

這是解決方案 -

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

爪哇11:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM