How do I know if a File type is PDF?

Well, kind of a hackish solution would be to look at the full file name and see if it ends in ".pdf". The following should help:

import javax.activation.*;  

public class ShowMimeType  
{  
    public static void main(String[] args) {  
        FileDataSource ds = new FileDataSource(args[0]);  
        String contentType = ds.getContentType();  
        System.out.println("The MIME type of the file " + args[0] + " is: " + contentType);  
    }  
}  

Well, according to wikipedia PDF files start with magic numbers: "%PDF" (hex 25 50 44 46) so maybe you should check the InputStream from the file and check that.


SimpleMagic is a Java library for resolving content types:

<!-- pom.xml -->
    <dependency>
        <groupId>com.j256.simplemagic</groupId>
        <artifactId>simplemagic</artifactId>
        <version>1.8</version>
    </dependency>

import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import com.j256.simplemagic.ContentType;
// ...

public class SimpleMagicSmokeTest {

    private final static Logger log = LoggerFactory.getLogger(SimpleMagicSmokeTest.class);

    @Test
    public void smokeTestSimpleMagic() throws IOException {
        ContentInfoUtil util = new ContentInfoUtil();
        File possiblePdfFile = new File("/path/to/possiblePdfFile.pdf");
        ContentInfo info = util.findMatch(possiblePdfFile);

        log.info( info.toString() );
        assertEquals( ContentType.PDF, info.getContentType() );
    }

Tags:

Java

Pdf