Java - File getName() method



Description

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.

Declaration

Following is the declaration for java.io.File.getName() method −

public String getName()

Parameters

NA

Return Value

This method returns name of the file or directory or empty string if pathname's name sequence in empty.

Exception

NA

Example - Getting the Name of a File

The following example shows the usage of Java File getName() method.

FileDemo.java

package 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.txt

Explanation

  • The full path "C:/Users/Anand/Documents/example.txt" is given.

  • getName() extracts and returns only the file name "example.txt".

Example - Getting the Name of a Directory

The following example shows the usage of Java File getName() method.

FileDemo.java

package 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: MyFolder

Explanation

  • The File object represents a directory, not a file.

  • getName() extracts and returns only the directory name "MyFolder".

Example - Handling a File Without a Path (Relative Path)

The following example shows the usage of Java File getName() method.

FileDemo.java

package 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.txt

Explanation

  • 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
Advertisements