How can I check to see if a java.io.File is a PDF file?

gdkinney_2
gdkinney_2 used Ask the Experts™
on
How can I check to see if a java.io.File is a PDF file?  I have a Java java.io.File type how can I determine if it's a PDF file type?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2016
Commented:
Check to see if its extension is .pdf? But a better way would be to check the header:

import java.io.*;

import java.util.*;


public class PdfChecker {
    public static void main(String[] args) {
        System.out.println(PdfChecker.isPdf(new File(args[0])));
    }

    public static boolean isPdf(File f) {
        boolean result = false;
        DataInputStream in = null;
        final byte[] PDF_HEADER = "%PDF".getBytes();
        byte[] buff = new byte[PDF_HEADER.length];

        try {
            in = new DataInputStream(new FileInputStream(f));
            in.readFully(buff);
            result = Arrays.equals(buff, PDF_HEADER);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) { /* ignore */
                }
            }

            return result;
        }
    }
}

Open in new window

Author

Commented:
If I send this a Word file that has a .pdf extension (for example "myfile.pdf" - actually a Word file) does this method return true or false?

Thanks
Top Expert 2016

Commented:
false. Try it ;)

Author

Commented:
Thanks CEHJ :).
Top Expert 2016

Commented:
:)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial