Home » Java programming language

Java File Class String getName() method with Example

Java File Class String getName() method: Here, we are going to learn about the String getName() method of File class with its syntax and example.
Submitted by Preeti Jain, on July 05, 2019

File Class String getName()

  • This method is available in package java.io.File.getName().
  • This method is used to retrieve or return the filename or directory name and represented by the file path.

Syntax:

    String getName(){
    }

Parameter(s):

We don't pass any object as a parameter in the method of the File.

Return value:

The return type of this method is String that means this method returns the name of file or directory and the name is in string type that's why return type of this method is a string.

Java program to demonstrate example of getName() method

// import the File class because we will use File class methods
import java.io.File;

//import the Exception class because it may raise an exception 
// when working with files
import java.lang.Exception;

public class GetNameOfFile {
    public static void main(String[] args) {
        try {
            // Specify the path of file and we use double slashes 
            // to escape '\' character sequence for windows otherwise 
            // it will be considerable as url.
            File file = new File("C:\\Users\\computer clinic\\OneDrive\\Articles\\myjava.txt");

            // By using getName() we can find the name of the file 
            // or directory and file should exists before 
            System.out.println("The Name Of The File created is : " + file.getName());

        } catch (Exception e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

Output

D:\Programs>javac GetNameOfFile.java

D:\Programs>java GetNameOfFile
The Name Of The File created is : C:\Users\computer clinic\OneDrive\Articles\myjava.txt





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.