Saturday, August 6, 2016

Getting the MIME Type based on filename

If you have worked with documents over internet (http), you must be aware of what MIME Type is.
(In case this has suddenly made you interested to read more about mime type, you can check this wiki link.)

But while doing coding in java, the traditional approach or at least how I had been working with so far is, to have a hash/map of mime types and then get it based on the file extension.

Now, here is what Java provides an interesting feature to remove your worries. :-)
There is this interesting feature since I guess, java 1.7,  in java.nio.Files -> probeContentType which gives you content type. here is small test to demo the same.


package com.java.test.demoprograms;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
public class ContentTypeTest {
Map<String, String> mimeMap = new HashMap<>();
@Before
public void beforeTest() {
mimeMap.put("pdf", "application/pdf");
}
@Test
public void testContentType() {
Path pathForPdf = Paths.get("Hello.pdf");
try {
assertEquals(mimeMap.get("pdf"), Files.probeContentType(pathForPdf));
} catch (IOException e) {
fail(String.format("Failed due to :%s", e.getMessage()));
}
}
}

Prototype

Prototype is another creation pattern. Intent:  - Intent is to create objects by cloning existing instance  - Specify the kinds of obj...