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

Java Program to Get the name of the file from the absolute path

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Get the name of the file from the absolute path
Java Program to Get the name of the file from the absolute path

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

PROGRAM: Java Program to Get the name of the file from the absolute path

/*Java Program to Get the name of the file from the absolute path*/

1: Get file name from the absolute path using getName()

import java.io.File;

class Main {

public static void main(String[] args) {

// link to file Test.class
File file = new File(“C:\\Users\\Sudip Bhandari\\Desktop\\Programiz\\Java Article\\Test.class”);

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

}
}

2: Get the file name using string methods

import java.io.File;

class Main {

public static void main(String[] args) {
File file = new File(“C:\\Users\\Sudip Bhandari\\Desktop\\Programiz\\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);
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *