Write a Java Program to Get the File Extension

Java Program to Get the File Extension

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 File Extension
Java Program to Get the File Extension

Write a Java Program to Get the File Extension

PROGRAM: Java Program to Get the File Extension

/*Java Program to Get the File Extension*/

1: Java Program to get the file extension

import java.io.File;

class Main {

public static void main(String[] args) {
File file = new File(“Test.java”);

// convert the file name into string
String fileName = file.toString();

int index = fileName.lastIndexOf(‘.’);
if(index > 0) {
String extension = fileName.substring(index + 1);
System.out.println(“File extension is ” + extension);
}
}
}

2: Get the file extension of all files present in a directory

import java.io.File;

class Main {

public static void main(String[] args) {
File directory = new File(“Directory”);

// list all files present in the directory
File[] files = directory.listFiles();
System.out.println(“Files\t\t\tExtension”);

for(File file : files) {
// convert the file name into string
String fileName = file.toString();

int index = fileName.lastIndexOf(‘.’);
if(index > 0) {
String extension = fileName.substring(index + 1);
System.out.println(fileName + “\t” + extension);
}
}
}

}

Leave a Reply

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