How to check whether file is gzip or not in java. I checked by reading first 2 bytes and comparing with magic code. But for large size of file getting OutOfMemoryError.
Any one knows other way to do this?
This is the code I am using:
def isGzipCompressionFile(File file)
{
return ((file.bytes[0] == (byte) (GZIPInputStream.GZIP_MAGIC)) && (file.bytes[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8)))
}
Use this package that I found on google:
package example;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.zip.GZIPInputStream;
public class GZipUtil {
/**
* Checks if an input stream is gzipped.
*
* @param in
* @return
*/
public static boolean isGZipped(InputStream in) {
if (!in.markSupported()) {
in = new BufferedInputStream(in);
}
in.mark(2);
int magic = 0;
try {
magic = in.read() & 0xff | ((in.read() << 8) & 0xff00);
in.reset();
} catch (IOException e) {
e.printStackTrace(System.err);
return false;
}
return magic == GZIPInputStream.GZIP_MAGIC;
}
/**
* Checks if a file is gzipped.
*
* @param f
* @return
*/
public static boolean isGZipped(File f) {
int magic = 0;
try {
RandomAccessFile raf = new RandomAccessFile(f, "r");
magic = raf.read() & 0xff | ((raf.read() << 8) & 0xff00);
raf.close();
} catch (Throwable e) {
e.printStackTrace(System.err);
}
return magic == GZIPInputStream.GZIP_MAGIC;
}
public static void main(String[] args) throws FileNotFoundException {
File gzf = new File("/tmp/1.gz");
// Check if a file is gzipped.
System.out.println(isGZipped(gzf));
// Check if a input stream is gzipped.
System.out.println(isGZipped(new FileInputStream(gzf)));
}
}
Try Files.probeContentType(Path) [JDK 7]
Path source = Paths.get("D:/myfiles/a.zip");
System.out.println(Files.probeContentType(source));
output
application/x-zip-compressed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With