Java File getName() Method

Java File Java File

getName()is an instance method provided by thejava.io.Fileclass in Java, used to get the name of a file or directory (excluding path information). This method returns a string representing the name part of the file object.

Method Syntax

public String getName()

Return Value

Returns a string representing the file or directory name (excluding path information).

Use Cases

getName()The method is particularly useful in the following situations:

  1. When you only need to get the file name without caring about its path
  2. Extracting file names in file list operations
  3. When you need to display or record file names
  4. When performing string operations related to file names

Example Code

Basic Usage Example

Example

import java.io.File;

public class GetNameExample {
    public static void main(String[] args) {
        // Create a File object
        File file = new File("C:/Users/Example/Documents/report.txt");
       
        // Use getName() to get the file name
        String fileName = file.getName();
       
        System.out.println("Full path: " + file.getPath());
        System.out.println("File name: " + fileName);
    }
}

Output Result

完整路径: C:\Users\Example\Documents\report.txt
文件名: report.txt

Directory Handling Example

Example

import java.io.File;

public class DirectoryNameExample {
    public static void main(String[] args) {
        // Create a File object pointing to a directory
        File directory = new File("C:/Program Files/Java");
       
        // Get the directory name
        String dirName = directory.getName();
       
        System.out.println("Directory name: " + dirName);
    }
}

Output Result

目录名: Java

Technical Details

Implementation Principle

getName()The method works as follows:

  1. First, get the full path string
  2. Then find the last path separator ("\" on Windows, "/" on Unix-like systems)
  3. Return the substring after the separator

Path Separator Handling

Java automatically handles path separator differences across operating systems, so no matter which separator you use,getName()it will work correctly.


Notes

  1. IfFilethe object represents a root directory (such as "C:" or "/"),getName()it will return an empty string ""
  2. This method does not check whether the file or directory actually exists
  3. The returned name includes the file extension (if any)
  4. For relative paths, only the last part of the path is returned

Comparison with Other Methods

getName() vs getPath()

  • getName(): Only returns the name part of the file or directory
  • getPath(): Returns the full path string used when creating the File object

getName() vs getAbsolutePath()

  • getName(): Only returns the name part
  • getAbsolutePath(): Returns the complete absolute path

Practical Application Examples

Batch Processing File Extensions

Example

import java.io.File;

public class FileExtensionExample {
    public static void main(String[] args) {
        File file = new File("data/archive.zip");
        String name = file.getName();
       
        // Get the file extension
        int dotIndex = name.lastIndexOf('.');
        if (dotIndex > 0) {
            String extension = name.substring(dotIndex + 1);
            System.out.println("File extension: " + extension);
        }
    }
}

Output Result

文件扩展名: zip

Traverse Directory and Get File Names

Example

import java.io.File;

public class ListFilesExample {
    public static void main(String[] args) {
        File directory = new File("C:/Users/Example/Downloads");
       
        // List all files in the directory
        File[] files = directory.listFiles();
       
        if (files != null) {
            System.out.println("Files in the download directory:");
            for (File file : files) {
                if (file.isFile()) {
                    System.out.println("- " + file.getName());
                }
            }
        }
    }
}

By mastering thegetName()method, you can more conveniently handle name information of files and directories, providing basic support for file operations.

Java File Java File

Other Extensions