Java 程式,用於從檔名中移除檔案資訊,只返回路徑部分


pathCompinent() 方法用於從檔名中刪除檔案資訊,僅返回其路徑部分。此方法需要一個引數,即檔名,並且它僅返回該檔名的路徑部分。

演示此方法的程式如下:

示例

 即時演示

import java.io.File;
public class Demo {
   public static String pathComponent(String fname) {
      int pos = fname.lastIndexOf(File.separator);
      if (pos > -1)
         return fname.substring(0, pos);
      else
         return fname;
   }
   public static void main(String[] args) {
      System.out.println(pathComponent("c:\JavaProgram\demo1.txt"));
   }
}

上述程式的輸出如下:

輸出

c:\JavaProgram

現在讓我們瞭解一下上述程式。

pathCompinent() 方法用於從檔名中刪除檔案資訊,僅返回其路徑部分。演示此方法的程式碼片段如下:

public static String pathComponent(String fname) {
   int pos = fname.lastIndexOf(File.separator);
   if (pos > -1)
      return fname.substring(0, pos);
   else
      return fname;
}

main() 方法列印該 pathComponent() 方法返回的檔名的路徑部分。演示此方法的程式碼片段如下:

public static void main(String[] args) {
   System.out.println(pathComponent("c:\JavaProgram\demo1.txt"));
}

更新於: 2019 年 7 月 30 日

110 次瀏覽

開始你的職業

完成課程即可獲得認證

開始
廣告