Java程序,用于从文件名中删除路径信息,仅返回其文件组件

该方法fileCompinent()用于从文件名中删除路径信息,并仅返回其文件组件。此方法需要一个参数,即文件名,它仅返回文件名的文件组成部分。

演示此的程序如下所示-

示例

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

上面程序的输出如下-

输出结果

demo1.txt

现在让我们了解上面的程序。

该方法fileComponent()用于从文件名中删除路径信息,并仅返回其文件组件。证明这一点的代码片段如下-

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

该方法main()打印该方法返回的文件名的文件部分fileComponent()。证明这一点的代码片段如下-

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