In Java development, it is often necessary to determine a file's type. For example, a file upload feature needs to check whether an uploaded file is of an allowed type. This article explains in detail how to obtain file types using Java.
I、Determining file type using the file extension
The most common way to determine a file's type is by its extension. Most files have a specific extension in an operating system; for example, the extension for a text file is usually .txt,image files usually have the extensions .jpg or.png and so on.
Getting a file extension in a Java program is very simple; just use String of the class substring method; the code is shown below:
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 "";
}
}This method accepts a File the object as a parameter, then use lastIndexOf method to find the position of the last dot in the filename, which marks the beginning of the extension, then use substring method retrieves and returns the file extension as a string. If the file has no extension, it returns an empty string.
You can test this method with the following code:
File file = new File("C:/path/to/file.txt");
String extension = getFileExtension(file);
System.out.println(extension);The output is:
txt
Using this method to determine file types has the following advantages:
Easy to use, with a concise code implementation.
Works for the vast majority of files, because the vast majority of files have filename extensions.
However, this method also has some drawbacks:
The file extension may have been changed, causing an incorrect determination.
Some files have no suffix, such as executable files without an extension.
To identify a file's type more accurately, we can also examine its magic number.

II、Identifying File Types Using Magic Numbers
A file's magic number consists of specific bytes among the first few bytes of the file, used to identify its type. By recognizing the magic number, we can accurately determine a file's type regardless of its filename extension.
In Java, you can obtain a file's magic number by reading its binary data.
2.1 Reading Binary Data from a File
We can use FileInputStream class to read a file’s binary data. The following method returns a byte array containing the file’s binary data:
public static byte[] readFileToByteArray(File file) throws IOException {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
byte[] data = new byte[(int)file.length()];
fis.read(data);
return data;
} finally {
if (fis != null) {
fis.close();
}
}
}The method above uses FileInputStream to open the file, read the data, and store it in a byte array. Note that after reading the file, you need to call close method closes the file stream to release system resources.
2.2 Determine the file type using magic numbers
With the file's binary data, we can determine its type. Each file type has a specific magic number that can be used to identify it. Below are the magic numbers for some common file types and the corresponding identification methods:
The magic number for text files (.txt) is
EF BB BF(UTF-8 encoded files have this byte sequence at the beginning), which can be checked using the following method:public static boolean isTextFile(byte[] data) { if (data.length >= 3 && data[0] == -17 && data[1] == -69 && data[2] == -65) { return true; } return false; }The magic number of a JPEG image (.jpg) is
FF D8 FF, the following method can be used to determine this:public static boolean isJPEGFile(byte[] data) { if (data.length >= 3 && data[0] == -1 && data[1] == -40 && data[2] == -1) { return true; } return false; }The magic number for PNG images(.png)is
89 50 4E 47 0D 0A 1A 0A, the following method can be used to determine this:public static boolean isPNGFile(byte[] data) { if (data.length >= 8 && data[0] == -119 && data[1] == 80 && data[2] == 78 && data[3] == 71 && data[4] == 13 && data[5] == 10 && data[6] == 26 && data[7] == 10) { return true; } return false; }
More file types and corresponding magic number detection methods can be added as needed.
2.3 Complete Example
Below is a complete example demonstrating how to identify file types using file magic numbers:
import java.io.File;import java.io.FileInputStream;import java.io.IOException;public class FileTypeChecker {
public static void main(String[] args) {
File file = new File("C:/path/to/file.jpg");
try {
byte[] data = readFileToByteArray(file);
if (isJPEGFile(data)) {
System.out.println("This is a JPEG file.");
} else if (isPNGFile(data)) {
System.out.println("This is a PNG file.");
} else if (isTextFile(data)) {
System.out.println("This is a text file.");
} else {
System.out.println("Unknown file type.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static byte[] readFileToByteArray(File file) throws IOException {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
byte[] data = new byte[(int)file.length()];
fis.read(data);
return data;
} finally {
if (fis != null) {
fis.close();
}
}
}
public static boolean isTextFile(byte[] data) {
if (data.length >= 3 && data[0] == -17 && data[1] == -69 && data[2] == -65) {
return true;
}
return false;
}
public static boolean isJPEGFile(byte[] data) {
if (data.length >= 3 && data[0] == -1 && data[1] == -40 && data[2] == -1) {
return true;
}
return false;
}
public static boolean isPNGFile(byte[] data) {
if (data.length >= 8 && data[0] == -119 && data[1] == 80 && data[2] == 78 && data[3] == 71 &&
data[4] == 13 && data[5] == 10 && data[6] == 26 && data[7] == 10) {
return true;
}
return false;
}
}The example code above determines the file type based on its magic number and outputs the corresponding result.
III. Using Third-Party Libraries to Determine File Types
In addition to the methods above, third-party libraries can also be used to determine file types. Java has some open-source third-party libraries that make identifying file types more convenient.
3.1 Tika
Tika is an Apache Software Foundation project that provides an open-source Java library for parsing various file formats, including text, images, audio, and video. Tika can extract file metadata, including the file type.
First, add the Tika library dependency. If you build your project with Maven, you can add it in pom.xml Add the following dependencies to the file:
<dependency> <groupId>org.apache.tika</groupId> <artifactId>tika-core</artifactId> <version>1.27</version> </dependency>
Then, you can use the following code to obtain the file type:
import org.apache.tika.Tika;
public class FileTypeChecker {
public static void main(String[] args) {
Tika tika = new Tika();
try {
File file = new File("C:/path/to/file.jpg");
String fileType = tika.detect(file);
System.out.println("File type: " + fileType);
} catch (IOException e) {
e.printStackTrace();
}
}
}Running the code above will output the file type.
Tika uses various methods to identify file types, including filename extensions and magic numbers. It also supports custom detectors, allowing you to add custom file type detection rules as needed.
3.2 FileTypeDetector
Java provides a standard API for detecting file types, namely FileTypeDetector Interfaces and ProbeContentType class. By implementing this interface, you can define a custom file type detector.
Here is an example of a custom file type detector:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.spi.FileTypeDetector;
public class CustomFileTypeDetector extends FileTypeDetector {
@Override
public String probeContentType(Path path) throws IOException {
String extension = getFileExtension(path.toFile());
if ("txt".equals(extension)) {
return "text/plain";
} else if ("jpg".equals(extension) || "jpeg".equals(extension)) {
return "image/jpeg";
} else if ("png".equals(extension)) {
return "image/png";
} else {
return null;
}
}
private String getFileExtension(File file) {
String fileName = file.getName();
if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
return fileName.substring(fileName.lastIndexOf(".") + 1);
} else {
return "";
}
}
}In this example, we determine the file type from its extension and return the corresponding MIME type.
To use a custom file type detector, add the following code at the program's entry point:
File file = new File("C:/path/to/file.jpg");
Path path = file.toPath();
String fileType = Files.probeContentType(path);
System.out.println("File type: " + fileType);Running the code above will output the file type.
Please note that for certain special file types, such as executables without filename extensions, this extension-based method may not be accurate enough. The method based on file magic numbers introduced earlier is therefore recommended.
IV、Summary
This article introduces several ways to determine file types in Java. You can identify a file's type by its extension or its magic number. Third-party libraries such as Tika make determining file types more convenient. For special file types, you can implement a custom file type detector for precise identification.
Choosing an appropriate way to determine a file's type depends on the specific application scenario and requirements. In actual development, select the most suitable detection method based on the file's characteristics and your requirements, while considering extensibility and compatibility.