java - 如何在Java中检查文件是否为gzip

标签 java gzip

如何在 java 中检查文件是否为 gzip。 我通过读取前 2 个字节并与魔术代码进行比较来检查。但是对于大文件,会出现 OutOfMemoryError。

有人知道其他方法吗?

这是我使用的代码:

def isGzipCompressionFile(File file)
{
   return ((file.bytes[0] == (byte) (GZIPInputStream.GZIP_MAGIC)) && (file.bytes[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8)))
}

最佳答案

使用我在 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)));
 }
}

关于java - 如何在Java中检查文件是否为gzip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30507653/

相关文章:

java - 使用 if 语句更改图像

javascript - Meteor Http 客户端 API 调用 Gzip 解压缩结果 JSON 不工作

Java 压缩大文件

java - JSF valueChangeListener 仅在第二次尝试时使用react?

java - 从计算机科学家到软件工程师

python:使用 gzip 文件遍历 tar 存档

python - 使用 Python 验证文件完整性

node.js - Nodejs express : compression of response doesn't work

java - java中的所有方法都是隐式虚拟的吗

java - 如何使用 Firebird 的 jaybird JDBC 驱动程序将绑定(bind)值设置为 NULL?