Get Name of a File from Absolute Path in Java

Exercise:

Write a Java Program to get the name of the file from the absolute path.

1.Get file name using getName()

Click Here to View the Solution!
import java.io.File;

class Main {
    public static void main(String[] args) {

        // link to file Test.class
        File file = new File("C:\\Users\\John Alan\\Desktop\\CodeOfCode\\Java Article\\Test.class");

        // get file name using getName()
        String fileName = file.getName();
        System.out.println("File Name: " + fileName);

    }
}
Click Here to View the Output!
File Name: Test.class
Click Here to View the Explanation!
  • This program is used to find the filename from an absolute path by using the .getName() method.
  • Initially, in the class Main, an object of the File is created that takes the absolute path of the file as its parameter.
  • The File class of Java provides a .getName() method that is used to get the name of the file from a given path. The filename obtained through .getName() is stored in a string variable fileName.
  • Finally, the string in filename is printed.

2.Get file name using string methods

Click Here to View the Solution!
import java.io.File;

class Main {

    public static void main(String[] args) {
        File file = new File("C:\\Users\\John Charles\\Desktop\\CodeOfCode\\Java Article\\Test.class");

        // convert the file into the string
        String stringFile = file.toString();
        int index = stringFile.lastIndexOf('\\');
        if(index > 0) {
            String fileName = stringFile.substring(index + 1);
            System.out.println("File Name: " + fileName);
        }
    }
}
Click Here to View the Output!
File Name: Test.class
Click Here to View the Explanation!
  • This program is used to find the name of a file from an absolute path using .toString() method in Java.
  • Initially, in a class Main, a file object is created that will take the absolute path of the file as a parameter.
  • The path of the file is first converted into a string using file.toString() method and store in stringFile variable.
  • A stringFile.lastIndexOf() method is used that will locate the final occurrence of of \\ in the path and store the value of index in variable index.
  • An if statement will check (index > 0), if true, then it will store the string after the index i.e. (index + 1) in the string variable filename using stringFile.substring() method.
  • Finally, the string in filename will be printed.
%d bloggers like this: