Get file name from a file location in Java

后端 未结 5 1369
野性不改
野性不改 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:32

    new File(fileName).getName();
    

    or

    int idx = fileName.replaceAll("\\\\", "/").lastIndexOf("/");
    return idx >= 0 ? fileName.substring(idx + 1) : fileName;
    

    Notice that the first solution is system dependent. It only takes the system's path separator character into account. So if your code runs on a Unix system and receives a Windows path, it won't work. This is the case when processing file uploads being sent by Internet Explorer.

提交回复
热议问题