On this document we will be showing a java example on how to use the getName() method of File Class. This method returns the name of the file or directory denoted by this abstract pathname. This is just the last name in the pathname’s name sequence. If the pathname’s name sequence is empty, then the empty string is returned.

Method Syntax

public String getName()

Method Argument

Data Type Parameter Description

Method Returns

This method returns a String which denotes the name of the file or directory denoted by this abstract pathname, or the empty string if this pathname’s name sequence is empty.


Requires Java 1.0 and up

Java File getName() Example

Below is a java code demonstrates the use of getName() method of File class. The example presented might be simple however it shows the behaviour of the getFreeSpace() method of File class. We have put a check if the file exists or not before we printed the getName() method.



 * This example source code demonstrates the use of  
 * getName() method of File class.

public class FileGetNameExample {

	public static void main(String[] args) {

		// initialize File object
		File file = new File("C:javatutorialhqinputtest_file.txt");

		boolean result;
		// check if file exists
			// print message that file exists
			System.out.println(file.getName() + " exists");
			//print message that the file does not exist
			System.out.println(file.getName()+" does not exists");

Sample Output

Below is the sample output when you run the above example.

java lang File getName() example output