Search code examples
javafilefile-read

Reading file type (MIME) returns null in Java


I'm editing a custom CSV importer that doesn't want to run on my system. My version of Java is: "1.8.0_171".

String contentType = Files.probeContentType(filePath);          
    //Should return "text/csv";
System.out.println("You have "+contentType+" type file.");
    //returns "You have null type file."

I've checked whether the file is accessible - it returns true.

System.out.println( "File is readable: " + Files.isReadable(filePath));
// returns: "File is readable: true"

What steps should I take next? I found some similar bugs:

https://bugs.java.com/view_bug.do?bug_id=JDK-7144997 https://bugs.openjdk.java.net/browse/JDK-8080369

I don't know whether they are related however.

UPDATE Updating Java to version "10.0.1" did not help.

UPDATE 2 Adding null to the list of allowed file types did work, however I consider this a HUGE hack, and this still needs resolving.


Solution

  • On Windows without any additional FileTypeDetector implementations installed Java will use default file type detector RegistryFileTypeDetector, which will return whatever has been associated with that extension on that particular machine, meaning whatever is under HKEY_CLASSES_ROOT\.csv is returned.

    If you want to enable some software to run consider installing custom FileTypeDetector on classpath via ServiceLoader mechanism or associating .csv with required value in registry.