- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get file extension name in Java
The file extension is the suffix that is attached to the computer file and it denotes the format of the file. A program that demonstrates getting the file extension name is given as follows −
Example
import java.io.File; public class Demo { private static String fileExtension(File file) { String name = file.getName(); if(name.lastIndexOf(".") != -1 && name.lastIndexOf(".") != 0) return name.substring(name.lastIndexOf(".") + 1); else return ""; } public static void main(String[] args) { File file = new File("demo1.txt"); System.out.println("The file extension is: " + fileExtension(file)); } }
The output of the above program is as follows −
Output
The file extension is: txt
Now let us understand the above program.
The method fileExtension() returns the file extension and it takes a single parameter i.e. the File class object. A code snippet that demonstrates this is given as follows −
private static String fileExtension(File file) { String name = file.getName(); if(name.lastIndexOf(".") != -1 && name.lastIndexOf(".") != 0) return name.substring(name.lastIndexOf(".") + 1); else return ""; }
The method main() calls the method fileExtension() and prints the file extension returned. A code snippet that demonstrates this is given as follows −
public static void main(String[] args) { File file = new File("demo1.txt"); System.out.println("The file extension is: " + fileExtension(file)); }
Advertisements