How to get the file extension in Java?
Last Updated :
20 Feb, 2024
In Java, a File Extension refers to the characters after the “.” in a file name. It denotes the file type. For example, in the file name document.pdf, the file extension is pdf. This indicates that the file is a PDF format file.
In this article, we will learn how to get the file extension in Java.
Example Input and Output:
Input: filePath = “\\Users\\Documents\\document.txt”
Output: txt
Input: filePath = “\\Users\\Documents\\image.png”
Output: png
Input: filePath = “\\Users\\Documents\\config_file”
Output: No extension
A dot separates the filename from its file extension. For instance, “picture.jpg” has the extension “jpg ” which tells us it’s an image file. By extracting this extension your program can determine the type of file. Take action, like opening it with the right software or processing its content based on its format.
Regular Expression: fileName.fileExtention
Program to Get the file extension in Java
Java offers various methods to complete this task. Here are the three most common approaches:
Approach 1: Manipulating strings manually
In this approach, we can utilize string manipulation to find the instance of the dot “.”. Then extract the characters that come after it. It doesn’t rely on any libraries. It is straightforward, for simple scenarios. It does necessitate handling of special cases such as files without extensions or, with multiple dots.
Example: In this example, we will find the extension of the given file by manipulating the string manually.
Java
import java.nio.file.Path;
public class StringManipulationExtractor {
public static void main(String[] args) {
String filePath = "C:\\Users\\Documents\\myFile.txt" ;
String filename = filePath.substring(filePath.lastIndexOf( '\\' ) + 1 );
int dotIndex = filename.lastIndexOf( '.' );
String extension = (dotIndex > 0 ) ? filename.substring(dotIndex + 1 ) : "" ;
System.out.println( "Extension: " + extension);
}
}
|
Explanation of the above Program:
- This Java program extracts the file extension from a given file path by manipulating the string manually.
- It first extracts the filename from the path, then finds the last occurrence of ‘.’ in the filename to determine the extension.
- At last, it prints the extracted extension.
Approach 2: By Using Java 8 Streams
This technique makes use of stream features to separate the filename using the dot “.” and obtain the part, which indicates the extension. This approach is compact and clear, for individuals who are familiar with streams. It can be combined with other stream operations. However it necessitates Java 8 or a newer version. It may have reduced efficiency when dealing with large datasets.
Example: In this example we will find the extension of the given file by Java stream.
Java
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
class Java8StreamsExtractor {
public static void main(String[] args) {
String filePath = "C:\\Users\\Documents\\report.pdf" ;
Path path = Paths.get(filePath);
String[] filenameParts = path.getFileName().toString().split( "\\." );
String extension = Arrays.stream(filenameParts)
.reduce((a, b) -> b)
.orElse( "" );
System.out.println( "Extension: " + extension);
}
}
|
Explanation of the above Program:
- This Java program extracts the file extension from a given file path using Java 8 streams.
- It splits the file name into parts using dots, then uses a stream to extract the last part, representing the extension.
- At last, it prints the extracted extension.
Approach 3: getExtension() Method
The Path class, in Java’s package provides a method called getFileName().toString().split(“\\. “)[1] which allows direct access to the file extension. This approach is concise and dependable although it assumes familiarity with the Path class. For developers who’re comfortable with Java NIO libraries this method offers a convenient and efficient solution, for extracting file extensions.
Example: In this example we will find the extension of the given file by getExtension() method.
Java
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileExtensionExtractor {
public static String getExtension(Path path) {
String fileName = path.getFileName().toString();
int dotIndex = fileName.lastIndexOf( '.' );
if (dotIndex == - 1 || dotIndex == fileName.length() - 1 ) {
return "" ;
} else {
return fileName.substring(dotIndex + 1 );
}
}
public static void main(String[] args) {
Path filePath1 = Paths.get( "C:\\Users\\Documents\\document.pdf" );
Path filePath2 = Paths.get( "C:\\Users\\Documents\\report" );
Path filePath3 = Paths.get( "C:\\Users\\Documents\\config.sys.old" );
System.out.println( "Extension of " + filePath1 + ": " + getExtension(filePath1));
System.out.println( "Extension of " + filePath2 + ": " + getExtension(filePath2));
System.out.println( "Extension of " + filePath3 + ": " + getExtension(filePath3));
}
}
|
Output
Extension of C:\Users\Documents\document.pdf: pdf
Extension of C:\Users\Documents\report:
Extension of C:\Users\Documents\config.sys.old: old
Explanation of the above Program:
- The
getExtension()
method takes a Path
object as input and extracts the file name from it.
- Using the
lastIndexOf()
method, it finds the last occurrence of the dot character in the file name.
- If no dot is found or the dot is at the end of the file name, it means there is no extension, so it returns an empty string.
- Or else, it extracts the substring after the dot as the file extension.
Share your thoughts in the comments
Please Login to comment...