java gzip无法保留原始文件的扩展名
我正在使用GZIPOutputStream将一个xml文件gzip到gz文件,但是在压缩后我发现gz文件层次结构中缺少xml文件(.xml)的扩展名。 我需要保留扩展名,因为压缩的gz文件将被第三方系统使用,它希望在解压缩gz文件后获得.xml文件。 这有什么解决方案吗? 我的测试代码是:
public static void main(String[] args) { compress("D://test.xml", "D://test.gz"); } private static boolean compress(String inputFileName, String targetFileName){ boolean compressResult=true; int BUFFER = 1024*4; byte[] B_ARRAY = new byte[BUFFER]; FileInputStream fins=null; FileOutputStream fout=null; GZIPOutputStream zout=null; try{ File srcFile=new File(inputFileName); fins=new FileInputStream (srcFile); File tatgetFile=new File(targetFileName); fout = new FileOutputStream(tatgetFile); zout = new GZIPOutputStream(fout); int number = 0; while((number = fins.read(B_ARRAY, 0, BUFFER)) != -1){ zout.write(B_ARRAY, 0, number); } }catch(Exception e){ e.printStackTrace(); compressResult=false; }finally{ try { zout.close(); fout.close(); fins.close(); } catch (IOException e) { e.printStackTrace(); compressResult=false; } } return compressResult; }
不知道这里有什么问题,你正在调用自己的压缩function
private static boolean compress(String inputFileName, String targetFileName)
使用以下参数
compress("D://test.xml", "D://test.gz");
很明显,你将丢失文件名的.xml部分,你永远不会将它传递给你的方法。
你的代码非常好。 将输出文件名称设为“D://test.xml.gz”,错过了文件扩展名(.xml)。
Ex: compress("D://test.xml", "D://test.xml.gz");
也许我错过了一些东西,但是当我过去gzip文件时,比如说test.xml
,我得到的输出就是test.xml.gz
也许如果您将输出文件名更改为test.xml.tz
您仍然可以保留原始文件扩展名。
您也可以在GZipping之前使用ArchiveOutput流(如Tar)。
将ZipOutputStream与ZipEntry一起使用,而不是使用GZipOutputStream。 这样它将保留原始文件扩展名。
示例代码如下..
ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(zipFile)); FileInputStream inStream = new FileInputStream(file); // Stream to read file ZipEntry entry = new ZipEntry(file.getPath()); // Make a ZipEntry zipOutStream.putNextEntry(entry); // Store entry
我创建了GZIPOutputStream的副本并更改了代码以允许“在gzip中”使用不同的文件名:
private final byte[] header = { (byte) GZIP_MAGIC, // Magic number (short) (byte)(GZIP_MAGIC >> 8), // Magic number (short) Deflater.DEFLATED, // Compression method (CM) 8, // Flags (FLG) 0, // Modification time MTIME (int) 0, // Modification time MTIME (int) 0, // Modification time MTIME (int) 0, // Modification time MTIME (int) 0, // Extra flags (XFLG) 0 // Operating system (OS) }; private void writeHeader() throws IOException { out.write(header); out.write("myinternalfilename".getBytes()); out.write(new byte[] {0}); }
有关gzip格式的信息: http : //www.gzip.org/zlib/rfc-gzip.html#specification