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
// Java program to get the file extension
// By manipulating String manually
import java.nio.file.Path;
public class StringManipulationExtractor {
public static void main(String[] args) {
// specify a file path
String filePath = "C:\\Users\\Documents\\myFile.txt";
// extract the filename from the path
String filename = filePath.substring(filePath.lastIndexOf('\\') + 1);
// find the last occurrence of '.' in the filename
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
// Java program to get the file extension using Stream
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
class Java8StreamsExtractor {
public static void main(String[] args) {
// Specify a file path
String filePath = "C:\\Users\\Documents\\report.pdf";
// Create a Path object for robust path handling
Path path = Paths.get(filePath);
// Extract the filename from the Path and split it into parts
String[] filenameParts = path.getFileName().toString().split("\\.");
// Extract the extension using a stream and reduce it to the last part
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
// Java program to get the file extension
// By using getExtension() method
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('.');
// handle cases with no extension or multiple dots
if (dotIndex == -1 || dotIndex == fileName.length() - 1) {
return ""; // no extension found
} 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"); // no extension
Path filePath3 = Paths.get("C:\\Users\\Documents\\config.sys.old"); // multiple dots
System.out.println("Extension of " + filePath1 + ": " + getExtension(filePath1));
System.out.println("Extension of " + filePath2 + ": " + getExtension(filePath2));
System.out.println("Extension of " + filePath3 + ": " + getExtension(filePath3));
}
}
OutputExtension 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.
Similar Reads
Java Program to Get the File Extension
The extension of a file is the last part of its name after the period (.). For example, the Java source file extension is âjavaâ, and you will notice that the file name always ends with â.javaâ. Getting the file extension in Java is done using the File class of Java, i.e., probeContentType() method.
2 min read
How to Get the Size of a File in Java?
In Java, file transferring, retrieving content of files, and manipulation of files developers frequently require the size of the file to perform proper file handling. In Java, there are many ways to get the size of the file. In this article, we will explore the most commonly used approaches to get t
3 min read
How to Get the File's Parent Directory in Java?
Java is one of the most popular and powerful programming languages. It is widely used for various purposes. In this article, we are going to learn how to find the parent directory of a file or a specified path. Methods to Get the Parent Directory of a fileIn Java, we can get the parent Directory wit
3 min read
How to Delete Temporary File in Java?
In java, we have a java.io package that provides various methods to perform various operations on files/directories. Temporary files are those files that are created for some business logic or unit testing, and after using these files you have to make sure that these temporary files should be delete
2 min read
How to Extract File Extension From a File Path String in Java?
In Java, working with Files is common, and knowing how to extract file extensions from file paths is essential for making informed decisions based on file types. In this article, we will explore techniques for doing this efficiently, empowering developers to improve their file-related operations. Pr
5 min read
How to Check if a File Exists in Java?
In Java programming, working with files is now a more common task. Developing a code to manage file automatization using Java. In this article, we will discuss how to check if a file exists in Java. By using the java.io.File class we will discuss two methods to check if a file exists or not. Approac
3 min read
File getTotalSpace() method in Java with examples
The getTotalSpace() function is a part of File class in Java . This function returns the total size of the partition denoted by the abstract pathname, if the pathname does not exist then it returns 0L. Function signature: public long getTotalSpace() Syntax: long var = file.getTotalSpace(); Parameter
2 min read
How to Read a File From the Classpath in Java?
Reading a file from the classpath concept in Java is important for Java Developers to understand. It is important because it plays a crucial role in the context of Resource Loading within applications. In Java, we can read a file from the classpath by using the Input Stream class. By loading the cla
3 min read
How to List all Files in a Directory in Java?
Java provides a feature to interact with the file system through the java.io.file package. This feature helps developers automate the things to operate with files and directories. In this article, we will learn how to list all the files in a directory in Java. Approaches to list all files in a direc
3 min read
Java Program to Get the Creation Time of a File
Use java.nio package for extracting the creation date and time of any file through java. To extract the date and time of the file use BasicFileAttributes class. java.nio package helps us to get the creation time, last access time, and last modified time, it works for both file and directory. Approac
2 min read