Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether file is gzip or not in Java

Tags:

java

gzip

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)))
}
like image 574
Snehal Kulkarni Avatar asked May 28 '15 13:05

Snehal Kulkarni


2 Answers

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)));
 }
}
like image 52
Luke Rixson Avatar answered Sep 28 '22 08:09

Luke Rixson


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
like image 31
Bacteria Avatar answered Sep 28 '22 07:09

Bacteria