Reading file header in java

Does anyone know how to read a file header in java using magic numbers or ascii to get the file extension name

+4
source share
2 answers

Perhaps not the answer you wanted, but since you gave us very little information ...

On unixoid systems (Linux, Mac, * BSD) you have the file command, which

checks each argument in an attempt to classify it. Three sets of tests are performed in this order: file system tests, magic tests, and language tests. The first test that succeeds causes file type printing.

eg.

$ 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 can call this program and analyze its output.

Change 1:

To determine if a given PNG file is:

 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 () also works for local files:

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

But your comments sound as if you should implement this method yourself, without using external programs (?).

+4
source

You can try JFileChooser . Here is an example.

 import java.io.*; import javax.swing.*; class GetFileType { public static void main(String[] args){ JFileChooser chooser = new JFileChooser(); File file = new File("Hello.txt"); String fileTypeName = chooser.getTypeDescription(file); System.out.println("File Type= "+fileTypeName); } } 

This will output a text document. If it is an MP3 file to be transferred, the output will sound in MP3 format.

+2
source

Source: https://habr.com/ru/post/1382007/


All Articles