To use Files.probeContentType(Path path) in Java, you simply pass a Path object to the method. It returns a string representing the MIME type (e.g., image/png, text/plain) or null if the type cannot be determined.
Here is a practical example of how to implement it:
package org.kodejava.nio;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ProbeContentTypeExample {
public static void main(String[] args) {
// Paths to different types of files
Path imagePath = Paths.get("logo.png");
Path textPath = Paths.get("example.txt");
Path htmlPath = Paths.get("google.html");
try {
// Detect and print the content types
System.out.println("Logo type: " + Files.probeContentType(imagePath));
System.out.println("Text type: " + Files.probeContentType(textPath));
System.out.println("HTML type: " + Files.probeContentType(htmlPath));
} catch (IOException e) {
e.printStackTrace();
}
}
}
Key points to remember:
- Implementation-Dependent: The detection mechanism depends on the installed
FileTypeDetectorimplementations and the underlying operating system. On Windows, it usually checks the registry based on the file extension. - Returns Null: If the system cannot determine the file type, it returns
nullrather than throwing an exception. - IOException: While rare for this specific method, it can throw an
IOExceptionif an I/O error occurs. - No Content Inspection: By default,
Files.probeContentTypeusually relies on file extensions and metadata rather than reading the actual byte content of the file. If you need deep content inspection (magic bytes), you might need a library like Apache Tika.
