我试图从互联网下载.torrent文件。一些在线文件是压缩(gzipped)格式。我知道我可以解压缩用下面的代码文件:不是GZIP格式Java
try (InputStream is = new GZIPInputStream(website.openStream())) {
Files.copy(is, Paths.get(path));
is.close();
}
但一些的.torrent文件都不会被压缩,因此我得到的错误信息:
java.util.zip.ZipException: Not in GZIP format
我处理一个.torrent文件的大型数据库,所以如果它被压缩,我不能一一解压。如何知道.torrent文件是否被压缩,并且只有在压缩文件时才解压缩文件?
伪代码:
if(file is compressed){
unzip
download
}else{
download
SOLUTION:
try (InputStream is = new GZIPInputStream(website.openStream())) {
Files.copy(is, Paths.get(path + "GZIP.torrent"));
is.close();
} catch (ZipException z) {
File f = new File(path + ".torrent");
FileOutputStream fos = new FileOutputStream(f);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
}
内容类型报头可以揭示该文件是否被压缩或不启动;你可以通过打开你的URL connection = website.openConnection(),然后打印connection.getContentType()来调试内容类型。 – Vulcan
请不要编辑问题以显示解决方案,但也可以将其添加为答案 – Mark
另外,依靠抛出异常来执行代码中的某些操作通常不是很好的做法......如果您可以检测它是否是在引发异常之前的gzip文件,它会好得多。在我看来,你可以用一个简单的'if(Paths.get(path).contains(“GZIP”)){/ *处理gzip代码/ *} else {/ *处理非gzip代码* /} – SnakeDoc