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?
It needs to be as general as possible as I cannot know in advance what the URL will be. I can't simply create a URL object and use getFile()
- all though that would have been ideal if it was possible - as it's not necessarily an http://
prefix it could be c:/ or something similar.
To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null. Syntax: public static string GetFileName (string path);
In Java, for NIO Path, we can use path. toAbsolutePath() to get the file path; For legacy IO File, we can use file. getAbsolutePath() to get the file path.
The mkdir() method is a part of File class. The mkdir() function is used to create a new directory denoted by the abstract pathname. The function returns true if directory is created else returns false. Parameters: This method do not accepts any parameter.
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.
new File(absolutePath).getName();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With