Reputation: 985
I will create a sample.txt
file. And then I will change extension of sample.txt
to sample.tar
How do I know the real type of the sample file?
Upvotes: 4
Views: 5365
Reputation: 2468
If you just want to know if a file is a tar file you can read the bytes 257, 258, 259, 260, 261. If they are ASCII 'ustar' it is a tar archive.
Upvotes: 0
Reputation: 12843
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 the Mime Type from a File.
Upvotes: 0
Reputation: 533510
A file only contains bytes. What you believe those bytes mean is entirely up to you. Any notion that a file has a real type is an illusion. For example you could have called it sample.txt but it was actually a TAR file.
There are tools to guess what the file format might be. However this is just a guess. A file doesn't have a "real" file type.
Upvotes: 5
Reputation: 236004
You can use a library such as Java Mime Magic to check if the supposed MIME type of the file matches its contents.
Upvotes: 2