从文件的绝对路径中获取文件名的 Java 程序

要理解此示例,您应该具备以下 Java 编程的知识:

示例 1:使用 getName() 从绝对路径获取文件名

import java.io.File;

public class Main {

  public static void main(String[] args) {

    // link to file Test.class
    File file = new File("C:\\Users\\Sudip Bhandari\\Desktop\\Program\\Java Article\\Test.class");

    // get file name using getName()
    String fileName = file.getName();
    System.out.println("文件名:" + fileName);

  }
}

输出

文件名:Test.class

在上面的例子中,我们使用了 File 类的 getName() 方法来获取文件名。

示例 2:使用字符串方法获取文件名

我们还可以使用字符串方法从绝对路径中获取文件的名称。

import java.io.File;

public class Main {

  public static void main(String[] args) {
    File file = new File("C:\\Users\\Sudip Bhandari\\Desktop\\Program\\Java Article\\Test.class");

    // convert the file into the string
    String stringFile = file.toString();

      int index = stringFile.lastIndexOf('\\');
      if(index > 0) {
        String fileName = stringFile.substring(index + 1);
        System.out.println("文件名:" + fileName);
      }
  }
}

输出

文件名:Test.class

在上面的例子中,

  • file.toString() - 将 File 对象转换为字符串。
  • stringFile.lastIndexOf() -返回字符 \\ 的最后一次出现的索引.
  • stringFile.substring(index + 1) - 返回位置 index + 1 之后的所有子字符串。