Get file name from a file location in Java

后端 未结 5 1371
野性不改
野性不改 2020-12-15 15:51

I have a String that provides an absolute path to a file (including the file name). I want to get just the file\'s name. What is the easiest way to do this?

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-15 16:14

    Here are 2 ways(both are OS independent.)

    Using Paths : Since 1.7

    Path p = Paths.get();
    String fileName = p.getFileName().toString();
    String directory = p.getParent().toString();
    

    Using FilenameUtils in Apache Commons IO :

    String name1 = FilenameUtils.getName("/ab/cd/xyz.txt");
    String name2 = FilenameUtils.getName("c:\\ab\\cd\\xyz.txt");
    

提交回复
热议问题