如何在java中检查文件是否为gzip。 我通过读取前2个字节并与魔术代码进行比较来检查。但是对于大尺寸的文件获取OutOfMemoryError。 任何人都知道其他方法吗?
答案 0 :(得分:6)
使用我在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)));
}
}
答案 1 :(得分:5)
尝试Files.probeContentType(Path) [JDK 7]
Path source = Paths.get("D:/myfiles/a.zip");
System.out.println(Files.probeContentType(source));
<强>输出强>
application/x-zip-compressed
答案 2 :(得分:2)
使用gzip输入流http://docs.oracle.com/javase/7/docs/api/java/util/zip/GZIPInputStream.html。如果您尝试打开另一种格式,它会抛出ZipException。在您的代码中,您可以在catchblock中捕获此异常。
答案 3 :(得分:1)
你应该只读取文件中的2个字节,如果你正在检查它,听起来就像是把整个文件拉进了内存。
https://docs.oracle.com/javase/tutorial/essential/io/datastreams.html
答案 4 :(得分:0)
这就是我正在使用的
private static void decompressGzipFile(String gzipFilePath, String newFilePath) {
try {
FileInputStream fis = new FileInputStream(gzipFile);
GZIPInputStream gis = new GZIPInputStream(fis);
// If this line does not throw exception your file is GZip
// Your logic
} catch (IOException e) {
//Not in GZip Format
}
}