Skip to content

Instantly share code, notes, and snippets.

@mohnish82
Created May 31, 2019 17:51
Show Gist options
  • Save mohnish82/00ce65bd6a536d8027604190d341a5ac to your computer and use it in GitHub Desktop.
Save mohnish82/00ce65bd6a536d8027604190d341a5ac to your computer and use it in GitHub Desktop.
[Java] Mime type detection
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileMimeTypeService {
public String getContentType(String file) {
String mimeType = null;
try { mimeType = fileInfoFromOs(file); } catch(Exception e) {}
if(mimeType == null)
try { mimeType = fileInfoFromJava(file); } catch(Exception e) {}
return mimeType;
}
protected String fileInfoFromJava(String file) throws Exception {
return Files.probeContentType(Paths.get(file));
}
protected String fileInfoFromOs(String file) throws Exception {
Process process = Runtime.getRuntime().exec("file -b --mime-type " + file);
int returnCode = process.waitFor();
if(returnCode != 0)
return null;
StringBuilder buff = new StringBuilder();
try(BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("UTF-8")))) {
String line = null;
while((line = reader.readLine()) != null) {
buff.append(line);
}
}
return buff.length() == 0 ? null : buff.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment