In this source code example, we show you how to get a file extension of a file in Java.
Get file extension of a file in Java
The below FileUtils class contains getFileExtension() utility method to get a file extension of a file in Java.package com.javaguides.javaio.utility;
import java.io.File;
/**
* Commonly used file utility methods.
* @author javaguides.net
*
*/
public class FileUtils {
/**
* Get file extension such as "txt","png","pdf"
* @param file
* @return
*/
public static String getFileExtension(File file){
String fileName = file.getName();
if(fileName.lastIndexOf('.') != -1 && fileName.lastIndexOf('.') != 0){
return fileName.substring(fileName.lastIndexOf('.')+1);
}else{
return "File don't have extension";
}
}
/**
* Check for file extension
* @param file
* @param extension
* @return
*/
public static boolean hasExtension(String file, String extension) {
return file.endsWith(extension);
}
}
Comments
Post a Comment