简体   繁体   中英

How to know a file type programmatically?

I work with 3 different types of file (XML, CSV and JSON) and I don't know which one I work at some point. I tried with some code, say,

File file = new File("src/main/java/data" + "/molecules.xml");
final MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
System.out.println(fileTypeMap.getContentType(file.getName()));

and it returns application/octet-stream and it goes same for .csv and the .json file as well. How do I get the correct file type ?

The correct MIME type will only show up if MimetypesFileTypeMap can match the file type using one of these resources:

  1. Programmatically added entries to the MimetypesFileTypeMap instance.
  2. The file .mime.types in the user's home directory.
  3. The file <java.home>/lib/mime.types .
  4. The file or resources named META-INF/mime.types .
  5. The file or resource named META-INF/mimetypes.default (usually found only in the activation.jar file).

The quickest solution is to use option #1 via addMimeTypes :

final MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
fileTypeMap.addMimeTypes("text/csv csv CSV");
fileTypeMap.addMimeTypes("application/json json JSON");
fileTypeMap.addMimeTypes("application/xml xml XML");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM