Java File getName() method with examples

January 04, 2020 No comments Java IO Examples File getName

1. Introduction

The getName() method returns the name of the file or directory. Note that this method returns only the last name in the pathname sequence.

2. Method signature

public String getName()

Parameters:

  • method does not take any parameter

Returns

  • String - the name of the file or directory

3. Examples

3.1. The program that prints the file and directory name using getName() method

package com.frontbackend.java.io.examples;

import java.io.File;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File file = new File("/tmp/frontbackend.txt");
            File dir3 = new File("/tmp/frontbackend/test");
            File dir2 = new File("/tmp/frontbackend");
            File tmp = new File("/tmp");
            File empty = new File("/");

            System.out.println(file.getName()); // frontbackend.txt

            System.out.println(dir3.getName()); // test

            System.out.println(dir2.getName()); // frontbackend

            System.out.println(tmp.getName()); // tmp

            System.out.println(empty.getName()); // 

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output:

frontbackend.txt
test
frontbackend
tmp

4. Conclusion

In this short article, we presented how to use File.getName() method in a single example. This method returns the simple name of the file or directory pointed by the File object.

{{ message }}

{{ 'Comments are closed.' | trans }}