Java tutorial
/* BetterFileTypeDetector.java: Detects file types using Brian White's mime.types file Copyright 2015 Bob W. Hogg. All Rights Reserved. This file is part of Git-VCR. Git-VCR is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Git-VCR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Git-VCR. If not, see <http://www.gnu.org/licenses/>. */ package com.github.rwhogg.git_vcr; import com.google.common.io.*; import java.io.*; import java.nio.charset.*; import java.nio.file.*; import java.nio.file.spi.*; import java.util.*; import org.apache.commons.io.*; /** * BetterFileTypeDetector detects file types using Brian White's mime.types file. */ public class BetterFileTypeDetector extends FileTypeDetector { /* typeMap is a mapping of file extensions to a single MIME-type (the first match we see) It is thus the REVERSE of how mime.types is structured. */ static final Map<String, String> typeMap; static { /* initialize the typemap. This algorithm is far from perfect - it just says that the first time we find a new file extension, we associate it with the corresponding mime type. So certain extensions which occur more than once may not map to what you consider their canonical mimetype. Oh well - this is still better than the provided FileTypeDetector on Mac OS X. */ typeMap = new HashMap<>(); try { List<String> typeLines = Resources.readLines(Resources.getResource("etc/mime.types"), Charset.forName("UTF-8")); for (String typeLine : typeLines) { String[] typeInfo = typeLine.trim().split("\\s+"); String mimetype = typeInfo[0]; if (typeInfo.length < 2) { continue; } for (int i = 1; i < typeInfo.length; i++) { String extension = typeInfo[i]; if (!typeMap.containsKey(extension)) { typeMap.put(extension, mimetype); } } } } catch (IOException e) { Util.error("could not load mime.types!"); } } /** * Provide a better implementation of probeContentType than we get on other platforms * @param path path to the file to determine the type of * @return The file's MIME type */ @Override public String probeContentType(Path path) throws IOException { return typeMap.get(FilenameUtils.getExtension(path.getFileName().toString())); } }