如何在 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/