Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file name from a file location in Java

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.

like image 328
Ankur Avatar asked Jun 18 '09 07:06

Ankur


People also ask

How do I find the filename of a file?

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);

How do I find the path of a file in Java?

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.

What is the type of the mkdir () method?

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.


2 Answers

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.

like image 148
akarnokd Avatar answered Sep 24 '22 05:09

akarnokd


new File(absolutePath).getName(); 
like image 36
victor hugo Avatar answered Sep 21 '22 05:09

victor hugo