本文介绍了java gzip无法保留原始文件的扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用GZIPOutputStream将一个xml文件压缩为gz文件,但是压缩后我发现gz文件层次结构中缺少xml文件的扩展名(.xml).我需要保留扩展名,因为第三方系统将使用压缩的gz文件,该第三方系统希望在解压缩gz文件后会得到一个.xml文件.有什么解决方案吗?我的测试代码是:

I'm using GZIPOutputStream to gzip one xml file to gz file, but after zipping I find the extension name of the xml file (.xml) is missing in the gz file hierarchy. I need to keep the extension name because the zipped gz file will be used by third party system which expects getting a .xml file after unzipping gz file. Are there any solutions for this? My test code is:

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;
}

推荐答案

不确定问题出在哪里,您正在调用自己的compress函数

Not sure what the problem is here, you are calling your own compress function

private static boolean compress(String inputFileName, String targetFileName)

具有以下参数

compress("D://test.xml", "D://test.gz");

很显然,您将丢失文件名的.xml部分,您永远不会将其传递到方法中.

Quite obviously you are going to lose the .xml portion of the filename, you never pass it into your method.

这篇关于java gzip无法保留原始文件的扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 15:14