How to check real file type in java?

I will create a sample.txt file. And then I will change the extension sample.txt to sample.tar

How to find out the real type of sample file?

+4
source share
4 answers

The file contains only bytes. What you think these bytes mean is entirely up to you. Any idea that the file is of a real type is an illusion. For example, you could name it sample.txt, but it was actually a TAR file.

There are tools to guess what file format might be. However, this is just an assumption. A file does not have a "real" file type.

+5
source

You can use a library such as Java Mime Magic to check if the intended MIME file type matches its contents.

+2
source
 import java.net.FileNameMap; import java.net.URLConnection; public class FileUtils { public static String getMimeType(String fileUrl) throws java.io.IOException { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String type = fileNameMap.getContentTypeFor(fileUrl); return type; } public static void main(String args[]) throws Exception { System.out.println(FileUtils.getMimeType("fileName.extension")); //for a.txt // output : text/plain } } 

This works fine if the file is not rar or compressed.

Refer to this link. Get Mime type from file.

0
source

If you just want to know if the tar file is a tar file, you can read bytes 257, 258, 259, 260, 261. If it is ASCII 'ustar', this is a tar archive.

0
source

All Articles