Search code examples
javafile-type

Reading the header of a file in java


Does any one know how to read the header of a file in java using "magic numbers" or ascii values to get the name of the extension of a file


Solution

  • Maybe not the answer you wanted, but as you gave us very little information ...

    In unixoid systems (Linux, Mac, *BSD) you have the file command, that

    tests each argument in an attempt to classify it. There are three sets of tests, performed in this order: filesystem tests, magic tests, and language tests. The first test that succeeds causes the file type to be printed.

    E.g.

    $ file linux-image-3.1.0-030100rc10-generic_3.1.0-030100rc10.201110200610_amd64.deb
    linux-image-3.1.0-030100rc10-generic_3.1.0-030100rc10.201110200610_amd64.deb: Debian binary package (format 2.0)
    

    Using Runtime.exec(...) you could invoke that program and parse its output.

    Edit 1:

    To determine if a given file is a PNG:

    import java.io.*;
    
    public class IsPng {
    
        public static void main(String ...filenames) throws Exception {
            if(filenames.length == 0) {
                System.err.println("Please supply filenames.");
                return;
            }
    
            for(String filename : filenames) {
                if(isPng(new File(filename))) {
                    System.out.println(filename + " is a png.");
                } else {
                    System.out.println(filename + " is _not_ a png.");
                }
            }
        }
    
        private static final int MAGIC[] = new int[] { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a };
    
        private static boolean isPng(File filename) throws Exception {
            FileInputStream ins = new FileInputStream(filename);
            try {
                for(int i = 0; i < MAGIC.length; ++i) {
                    if(ins.read() != MAGIC[i]) {
                        return false;
                    }
                }
                return true;
            } finally {
                ins.close();
            }
        }
    
    }
    

    Edit 2:

    Sometimes URLConnection.getContentType() works, too, for local files:

    new File(name).toURI().toURL().openConnection().getContentType()
    

    But your comments sound like you have to implement the method by yourself, not using external programs (?).