The Java File getName() method returns the last name of the pathname's name sequence, that means the name of the file or directory denoted by this abstract path name is returned.
DeclarationFollowing is the declaration for java.io.File.getName() method −
public String getName()Parameters
NA
Return ValueThis method returns name of the file or directory or empty string if pathname's name sequence in empty.
ExceptionNA
Example - Getting the Name of a FileThe following example shows the usage of Java File getName() method.
FileDemo.javapackage com.tutorialspoint; import java.io.File; public class FileDemo { public static void main(String[] args) { File file = new File("C:/Users/Anand/Documents/example.txt"); System.out.println("File Name: " + file.getName()); } }Output
Let us compile and run the above program, this will produce the following result −
File Name: example.txtExplanation
The full path "C:/Users/Anand/Documents/example.txt" is given.
getName() extracts and returns only the file name "example.txt".
The following example shows the usage of Java File getName() method.
FileDemo.javapackage com.tutorialspoint; import java.io.File; public class FileDemo { public static void main(String[] args) { File directory = new File("C:/Users/Anand/Documents/MyFolder"); System.out.println("Directory Name: " + directory.getName()); } }Output
Let us compile and run the above program, this will produce the following result −
Directory Name: MyFolderExplanation
The File object represents a directory, not a file.
getName() extracts and returns only the directory name "MyFolder".
The following example shows the usage of Java File getName() method.
FileDemo.javapackage com.tutorialspoint; import java.io.File; public class FileDemo { public static void main(String[] args) { File file = new File("example.txt"); // Relative path System.out.println("File Name: " + file.getName()); } }Output
Let us compile and run the above program, this will produce the following result −
File Name: example.txtExplanation
The file "example.txt" is specified without a full path.
getName() simply returns "example.txt", as no directory information exists.
java_io_file_methods.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4